我目前正在对一个API进行ajax调用,从端点检索回数据。我能够成功调用API。当控制台记录 data.Results.Data[110].DataValue
我得到的结果是 22,121 这正是我所期望的。我现在正试图在我创建的高图表中使用这些数据。但当我这样做时,我被一个错误卡住了,说明 “数据未定义”。我如何访问 “数据”?data
所以我可以正确使用 data.Results.Data[110].DataValue
在我的图中?
这是我的代码。
/* page preloader */
$(window).on("load", function (e) {
$('.preloader').fadeOut('slow');
$.ajax({
type: "GET",
url: gspUrl,
async: true,
success: function (data) {
console.log(data.Results.Data[110].DataValue, "test")
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
});
//Graph
Highcharts.chart('container', {
chart: {
type: 'line'
},
title: {
text: 'State Information'
},
xAxis: {
categories: ['1997', '1999', '2001', '2003', '2005', '2007', '2009', '2012', '2014', '2016', '2018'],
title: {
text: 'Year'
},
},
yAxis: {
categories: ['2', '4', '6', '8', '10'],
title: {
text: 'Percentage Change (%)'
}
},
plotOptions: {
line: {
dataLabels: {
enabled: false
},
enableMouseTracking: false
}
},
series: [{
name: 'State',
data: [data.Results.Data[110].DataValue, 2.9, 3.5, 4.5, 8.4, 1.5, 5.2, 6.5, 3.3, 8.3, 3.9],
color: '#002F65'
}, {
name: 'US',
color: '#0B7070',
data: [3.9, 4.2, 5.7, 8.5, 1.9, 5.2, 7.0, 6.6, 4.2, 5.3, 10]
}]
});
我试图使用 data
根据 series
的部分。我怎样才能在图形中访问来自ajax调用的数据?
解决方案:
你检索数据的代码是异步的。这意味着你的代码没有以你最可能期望的线性方式运行。
你需要把绘制图表的代码移到你的成功回调中,或者把它包在自己的函数中,并按下面的方式调用它。
$(window).on("load", function (e) {
$('.preloader').fadeOut('slow');
$.ajax({
type: "GET",
url: gspUrl,
async: true,
success: function (data) {
drawGraph(data.Results.Data[110].DataValue); // Call a function that now wraps your graph call
console.log(data.Results.Data[110].DataValue, "test")
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
});
// Graph
function drawGraph(dataValue) {
Highcharts.chart('container', {
chart: {
type: 'line'
},
title: {
text: 'State Information'
},
xAxis: {
categories: ['1997', '1999', '2001', '2003', '2005', '2007', '2009', '2012', '2014', '2016', '2018'],
title: {
text: 'Year'
},
},
yAxis: {
categories: ['2', '4', '6', '8', '10'],
title: {
text: 'Percentage Change (%)'
}
},
plotOptions: {
line: {
dataLabels: {
enabled: false
},
enableMouseTracking: false
}
},
series: [
{
name: 'State',
data: [dataValue, 2.9, 3.5, 4.5, 8.4, 1.5, 5.2, 6.5, 3.3, 8.3, 3.9],
color: '#002F65'
},
{
name: 'US',
color: '#0B7070',
data: [3.9, 4.2, 5.7, 8.5, 1.9, 5.2, 7.0, 6.6, 4.2, 5.3, 10]
}
]
});
}