繁体   English   中英

jQuery $ .getJSON错误

[英]jquery $.getJSON error

使用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

试试这个( 此工作 ):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM