[英]Scope of an array filled inside a jQuery getJson function
我正在尝试使用多个jQuery的get JSON函数多次填充数组。 并在插入所有数据后使用该数组。
问题在于数据仅在每个函数内部作用域,而我无法使用多个单独的函数来填充数组,例如:
var array;
array = [];
//Now I use getJSON to call a php with a json output and push the response
$.getJSON('../includes/comOne.php', function(response){
//Here I get a JSON formated object that I push into the array
array.push(response);
一切都很好,如果我记录数组,我会得到在JSON对象中创建的对象实体和每个值。
console.log(array)
输出:
[Array [2]] 0:Array [2] 0:ObjectdateUpdate:“ 2015-04-04 19:39:16” intID:“ 1” strDate:“ 56” strFfb:“ tete” str图:“ tete” strFront: “ testrfront” strFtw:“ tete” strHeader:“ testhe” strText:“ testtext” strType:“ Native” strVideo:“ tete” 原型 :Object1:ObjectdateUpdate:“ 2015-04-04 19:39:16” intID:“ 2 “strDate: “12” strFfb: “FSF” strFig: “sfsfs” strFront: “fsfsfsfsfsf” strFtw: “sfsfsfs” strHeader: “tetetetetetetetetetetete” strText中: “fsfsfsfsfsfsf” strType: “天然” strVideo: “FS” 原 :Objectlength: 2__proto__:数组[0]长度:1__proto__:数组[0]
})
但是,如果我尝试将数组记录到getJSON函数之外,则该数组为空
console.log(array);
输出:
[]
我试图在变量内创建json函数并返回响应,但是我松开了数组。
谢谢!
那是因为您的ajax函数是异步的:触发ajax请求,然后继续显示该数组。 由于$.getJSON()
函数尚未完成,因此该$.getJSON()
仍为空。
您应该检查所有ajax请求均已完成,然后才能使用该数组。 您可以为此使用$.when()
类的东西。
例如:
var array = [],
call1 = $.getJSON(...),
call2 = $.getJSON(...);
$.when(call1, call2).then(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.