在jQuery getJson函数中填充的数组的范围
我想用多个jQuery的JSON函数来多次提供数组。所有数据插入后使用该数组。在jQuery getJson函数中填充的数组的范围
的问题是,该数据仅作用域每个功能内,我不能喂具有多个独立的功能的阵列,例如:
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)
输出:
[阵列[2]] 0: 数组[2] 0: ObjectdateUpdate: “2015-04-09 19时39分16秒” INTID:“ 1“ strDate:”56“ strFfb:”tete“strFig:”tete“strFront:”testrfront“strFtw:”tete“strHeader:”testhe“strText:”testtext“strType:”Native“strVideo:”tete“proto:Object1:ObjectdateUpdate:“2015-04-04 19:39:16”intID:“2”strDate:“12”strFfb:“fsf”strFig:“sfsfs”strFront:“fsfsf sfsfsf“strFtw: ”sfsfsfs“ strHeader: ”tetetetetetetetetetetete“ strText中: ”fsfsfsfsfsfsf“ strType: ”天然“ strVideo: ”FS“ 原:Objectlength:2__proto__:数组[0]长度:1__proto__:数组[0]
})
但是,如果我尝试登录阵列外部的功能的getJSON数组为空
输出:
[]
我试着在一个变量里面创建json函数并返回响应,但是我失去了这个数组。
谢谢!
这是因为你的ajax函数是异步的:你激发你的ajax请求,然后你继续显示数组。这仍然是空的,因为$.getJSON()
函数尚未完成。
你应该检查你的所有ajax请求都已完成,然后才能使用该数组。你可以使用像$.when()
这样的东西。
例如:
var array = [],
call1 = $.getJSON(...),
call2 = $.getJSON(...);
$.when(call1, call2).then(...);
你说得对,我也没多想它。很好的答案,谢谢! – nach 2015-04-04 19:34:13