简体   繁体   中英

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. 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.

    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]

})

But if I try to log the array outside the getJSON function the array is empty

console.log(array);

Output:

[]

I've tried to create the json function inside a variable and return the response, but I loose the array.

Thanks!

That is because your ajax function is asynchronous: You fire your ajax request and then you move on to show the array. That will still be empty because the $.getJSON() function has not finished yet.

You should check that all your ajax requests are finished and only then use the array. You can use something like $.when() for that.

For example:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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