gpt4 book ai didi

javascript - 将 Thymeleaf 与 Google 图表和 Java map 结合使用

转载 作者:行者123 更新时间:2023-11-30 20:39:42 26 4
gpt4 key购买 nike

我用 JavaScript 制作的 Thymeleaf block 切断了结尾;变量,并抛出 Uncaught (in promise) SyntaxError: Unexpected token ' in JSON at position 2

除数据变量外,代码确实按应有的方式进行了解析。解析代码:

function drawChart() {

var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";

var data = {'Expense1': 25.0, 'Expense2': 20.0, 'Expense3': 40.0};
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);

var json = JSON.parse(res);

var data = new google.visualization.DataTable(json);

var options = {
title: 'Data test',
pieHole: 0.4
};

var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}

Pre Thymeleaf 代码:

<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";

var data = /*[[${chart.DataPoints}]]*/;
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);

var json = JSON.parse(res);

var data = new google.visualization.DataTable(json);

var options = {
title: /*[[${chart.title}]]*/'',
pieHole: 0.4
};

var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>

data var 要么像现在一样,要么当包含在 ""中时,它会 chop 结束分号。如何让 JavaScript 的 Thymeleaf 将数据 var 转换为字符串(同时保持它包含的 '')?

最佳答案

这对你有用吗?我认为您不需要先将数据构建为 JSON 字符串,只需将其创建为 JavaScript 对象即可:

<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var json = {
'cols': [
{'id':'', 'label': 'Expense', 'pattern': '', 'type': 'string'},
{'id':'', 'label': 'Amount', 'pattern': '', 'type': 'number'}
],
rows: []
};

var data = /*[[${chart.DataPoints}]]*/ [];
var rows = [];
Object.keys(data).forEach(function(key) {
rows.push({
"c": [
{"v": key, "f": null},
{"v": data[key], "f": null}
]
});
});

json['rows'] = rows;

var data = new google.visualization.DataTable(json);
var title = /*[[${chart.title}]]*/ '';
var options = {
title: title,
pieHole: 0.4
};

var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
  • 编辑:您可以根据需要格式化数据...用 JavaScript 做起来非常简单。

关于javascript - 将 Thymeleaf 与 Google 图表和 Java map 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com