簡體   English   中英

填充在jQuery getJson函數內部的數組的范圍

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM