简体   繁体   English

填充在jQuery getJson函数内部的数组的范围

[英]Scope of an array filled inside a jQuery getJson function

I'm trying to feed an array several times using multiple jQuery's get JSON functions. 我正在尝试使用多个jQuery的get JSON函数多次填充数组。 And use the array after all the data is inserted. 并在插入所有数据后使用该数组。

The problem is that the data only scopes inside each function and I can't feed the array with multiple separate functions, for example: 问题在于数据仅在每个函数内部作用域,而我无法使用多个单独的函数来填充数组,例如:

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);

Everything is fine and if I log the array I get the object entities created in the JSON objects and each value. 一切都很好,如果我记录数组,我会得到在JSON对象中创建的对象实体和每个值。

    console.log(array)

Output: 输出:

[Array[2]]0: Array[2]0: ObjectdateUpdate: "2015-04-04 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: "fsfsfsfsfsf"strFtw: "sfsfsfs"strHeader: "tetetetetetetetetetetete"strText: "fsfsfsfsfsfsf"strType: "Native"strVideo: "fs" proto : Objectlength: 2__proto__: Array[0]length: 1__proto__: Array[0] [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]

})

But if I try to log the array outside the getJSON function the array is empty 但是,如果我尝试将数组记录到getJSON函数之外,则该数组为空

console.log(array);

Output: 输出:

[] []

I've tried to create the json function inside a variable and return the response, but I loose the array. 我试图在变量内创建json函数并返回响应,但是我松开了数组。

Thanks! 谢谢!

That is because your ajax function is asynchronous: You fire your ajax request and then you move on to show the array. 那是因为您的ajax函数是异步的:触发ajax请求,然后继续显示该数组。 That will still be empty because the $.getJSON() function has not finished yet. 由于$.getJSON()函数尚未完成,因此该$.getJSON()仍为空。

You should check that all your ajax requests are finished and only then use the array. 您应该检查所有ajax请求均已完成,然后才能使用该数组。 You can use something like $.when() for that. 您可以为此使用$.when()类的东西。

For example: 例如:

var array = [],
    call1 = $.getJSON(...),
    call2 = $.getJSON(...);

$.when(call1, call2).then(...);

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

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