jquery $ .getJSON错误

时间:2014-05-03 20:10:11

标签: javascript jquery json

使用Float Charts jquery工具,数据var值就像那样

var d2 = [[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]

当我使用$ .getJSON

将其更改为来自请求时
 var d2 = var d2 = $.getJSON( "UpdateCharts", function() { ......

响应返回

[[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]

但是我得到一个错误,即d2值为0而不是第一个值

Uncaught TypeError: Cannot read property '0' of undefined

1 个答案:

答案 0 :(得分:1)

试试这个(这个工作):

var d2;
$.getJSON( "path/to/json/file", function(data) { 
   // parse data to the d2
   // d2 = data; // <-- use this if you want same array/object structure like json file contents has
   console.log(d2); // <-- this will output correct d2 contents 
}

而不是这个(示例如何不做):

var d2 = $.getJSON( "path/to/json/file", function(data) { 
   // parse data to the d2
}
console.log(d2); // <-- this will show error/wrong contents, because it is shown before json data was parsed

出现错误,因为getJSON是异步函数。您只需定义将在某些事情发生时执行的操作。使用getJSON,您可以在从外部存储加载数据时定义操作。您可以在参数中指定的函数中精确输出数据,但不能在之后输出。

示例:

1. // this part is executing first, order: 1
2. var xxx = $.getJSON( "xxx", function(xxx) { // you just specified what to do when data will be parsed there
3.    // this part will be called after all contents will be loaded, order: 3
4. }
5. // this part is executing right after 1st lane, order: 2