数据未定义,但可以在console.log-Javascript中查看数据



我目前正在对API进行ajax调用,该调用从端点检索回数据。我能够成功地调用API。当控制台记录data.Results.Data[110].DataValue时,我会返回结果22211,这正是我所期望的。我现在正试图在我创建的高图表中使用这些数据。但在这样做的时候,我陷入了一个错误,说"数据没有定义"。如何访问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]
}]
});

我试图在图的series部分下使用data。我如何能够访问图形中来自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]
}
]
});
}

最新更新