我有这张特别的表:
<div class="chartHeader"><p>Performance statistics summary</p></div>
<table id="tableSummary">
<tr>
<th>Measurement name</th>
<th>Result</th>
</tr>
<tr>
<td>Total messages sent</td>
<td id = "totalMessagesSent"></td>
</tr>
<tr>
<td>Total messages processed</td>
<td id = "totalMessagesProcessed"></td>
</tr>
<tr>
<td>Average messages per second</td>
<td id = "averageMessagesPerSecond"></td>
</tr>
</table>
在磁盘上的某个地方,我在groovy中生成了这样的json:
{
"reportSummary": {
"totalMessagesSent": 23,
"totalMessagesProcessed": 10384,
"averageMessagesPerSecond": 2.3E-8
}
}
我想通过使用javascript来填充上面的表格和json的日期,试过很多版本但是无法制作它,在我添加的html页面中:
<script type="text/javascript">fillTableWithData('reportSummary.json');</script>
目前脚本是这样的,但它不起作用:
function fillTableWithData(filename) {
var reader = new FileReader();
var jsonFile = reader.readAsText(filename);
var jsons = d3.json(jsonFile);
d3.select("#totalMessagesSent").append(jsons.totalMessagesSent);
d3.select("#totalMessagesProcessed").append(jsons.totalMessagesProcessed);
d3.select("#averageMessagesPerSecond").append(jsons.averageMessagesPerSecond);
}
有人可以建议我如何正确地做到这一点吗?我花了太多时间在上面,我目前没有想法......任何帮助表示赞赏。提前谢谢。
编辑:如果在纯粹的js中更容易,我根本不需要在这里使用d3 ......
答案 0 :(得分:0)
该问题的解决方案如下:
function fillTableWithData(filename) {
var data_file = filename;
var http_request = new XMLHttpRequest();
try {
http_request = new XMLHttpRequest();
} catch (e) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
var jsonObj = JSON.parse(http_request.responseText);
document.getElementById("messagesSent").innerHTML = jsonObj.reportSummary.messagesSent;
document.getElementById("tradeEventsProcessed").innerHTML = jsonObj.reportSummary.tradeEventsProcessed;
document.getElementById("averageMessagesPerSecond").innerHTML = jsonObj.reportSummary.averageMessagesPerSecond;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
我们不能简单地使用js来加载文件,因为它在客户端工作。