2017-05-25 81 views
0

我有一個AJAX正從分貝值,並且將結果推入的數組:提取陣列 - 未定義

function pushPONFail(dt, ct) { 
    if (ct < 12) { 
     var tMon = parseInt(dt.getMonth())+1; 
     var tYear = dt.getFullYear(); 

     ct++; 
    } else { 
     return; 
    } 
    data = {"qType": 101, 
      "tbl": 'qualitypqa.dbo.centerthickness', 
      "month": tMon, 
      "year": tYear, 
      "type": 'Lotrafilcon B'}; 
    $.ajax({ 
     cache : false, 
     url: "getrpt.php", 
     type: "get", 
     data: data, 
     contentType: 'application/json; charset=utf-8', 
     async: true, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
     console.log("error: "+textStatus+" : "+errorThrown); 
     } 
    }) 
    .done(function(response){ 
     var obj = jQuery.parseJSON(JSON.stringify(response)); 
     arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail}); 
     dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1)); 
     pushPONFail(dt, ct); 
    }); 

} // pushing values such as ["May/2017", 0] 

$(function() { 
    var dt = new Date(); 
    pushPONFail(dt, 0); 

    console.log(arrPONFail); 
}); 

這些是完整的功能。當我console.log數組時,它出現在我的照片中。我無法提取數據。

當我將數組打印到控制檯時,如下圖所示。

如何從數組中返回值? 當我做一個arrT [0]時,我得到一個未定義的。

請指教。

enter image description here

+0

您是在.done()之外的控制檯日誌記錄arrT。 done()完成後,您應該控制日誌arrT,或者您可以在1000毫秒內調用timeout函數,然後記錄arrT。你會看到不同之處。 – supritshah1289

回答

0

這很可能是一個異步的問題 - 你訪問.done()功能arrT[0]之外?如果是這樣,當你訪問它時,數組中沒有任何東西 - 它是空的。您所做的ajax請求需要一些時間(毫秒),並且只有在數據返回後,您的數組纔有內容。要使用數組中的值,請嘗試將使用該數組的代碼放在.done()函數本身內。

+0

問題是,我使用回調系統來避免在ajax中輸入async:false。如果我做async:false,則值被正確定義。在.done()之後,我做了一個console.log(arrT),並且我得到了我附加的圖片,這意味着值就在那裏,對嗎?只有當我試圖提取的價值,然後我有未定義的。 – rherry

+0

嘗試'done()'函數內的console.logging。如果你在外面做,你會遇到異步問題,因爲'done()'函數之外的所有代碼都會最後運行。 –