gpt4 book ai didi

javascript - 使用外部 JSON 数据构建 highchart 图表

转载 作者:行者123 更新时间:2023-12-02 15:39:02 25 4
gpt4 key购买 nike

我正在尝试使用 JQuery 读取 highcharts 图表中的 JSON 文件,但失败了。我在文件中找到了这个 JSON:

[{"Bellman-Ford": {"totalRate": 1.123, "way": [], "time": 0.00014495849609375}}, {"genetic": {"totalRate": 1.4566, "way": [], "time": 0.1541710883}}, {"recuit": {"totalRate": 1.782, "way": [], "time": 0.00004728945}}]

我的图表是这样的:

$(function () {
$('#rate').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Comparison of the final rates'
},
subtitle: {
text: 'DNF'
},

yAxis: {
min: 0,
title: {
text: 'Rate (USD)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
animation : true,
series: [{
name: 'Bellman-Ford',
data: [49.9] //bf rate

}, {
name: 'Genetic Algorithm',
data: [83.6] // genetic rate

}, {
name: 'Recuit',
data: [34.6] // recuit rate

}]
});
});

我想使用 JSON 中的数据,而不是那些硬编码数据。每种算法(遗传算法、模拟退火算法和贝尔曼福特算法)的速率数据。我想我没有很好地理解异步函数的问题。

最佳答案

  1. 我们检索 JSON,它由 jQuery 自动解析
  2. 我们循环主数组以使用 for of 获取对象直接访问对象
  3. 我们使用 for in 循环遍历对象访问属性名称,然后访问数据本身

数据和图表是在收到 JSON 后使用 done() 构建的。方法 jQuery.ajax() .

$(function () {

// get the json
$.ajax({
url: "result.json",
dataType: "json",
}).done(function(myData) {

// initialize the data array
var mySeries = [];

// loop through the objects
for(var myObj of myData) {

// loop through the object's properties (seemingly only one)
for(var myName in myObj) {

// build data
mySeries.push({
name : myName,
data : [myObj[myName].totalRate],
});
}
}

$('#rate').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Comparison of the final rates'
},
subtitle: {
text: 'DNF'
},

yAxis: {
min: 0,
title: {
text: 'Rate (USD)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
animation : true,
series: mySeries
});
});
});

然后我们可以在图表选项中使用它:

series: mySeries

更新2015-09-23 15:35 +0000

这是针对此答案的评论的快速说明。

OP 在评论中说:

I've got a syntax error: Uncaught SyntaxError: Unexpected identifier: for(var myObj of myData) {

另一条评论说:

Change: for(var myObj of myData) {..} to for(var myObj in myData) {..}

使用for...in迭代索引而不是值,这需要使用 myData[myObj]访问底层对象。也有一段时间使用for...in数组返回其 length 属性,这是不希望的,需要使用 for(var i=0; i<array.length; ++i) .

MDN 文档中的更多详细信息:

关于javascript - 使用外部 JSON 数据构建 highchart 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32723964/

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