[英]Pushing objects into an array in Javascript after extracting from JSON response
[英]Pushing to Javascript Array from Jquery JSON request
為什么這段代碼總是返回0?
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length);
雖然我可以移動或添加“alert(possibleMatches.length);” 在$ .each中,它將輸出正確數量的元素。
我只是好奇為什么價值不像我預期的那樣進入數組。 我確定它是局部變量與全局變量問題,只是不確定原因。
基本上,這是嘗試做的是使用數據結果填充possibleMatches數組。
謝謝!
異步。 行alert(possibleMatches.length);
在$.getJSON()
執行成功回調之前執行。
因此,要准確地提供警報報告,只需移動它即可。
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
// To here
alert(possibleMatches.length);
});
// From here
請記住,AJAX中的第一個A代表“異步”
$.getJSON
執行異步調用,其回調在完成使用的xmlhttprequest時執行:
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) { // <-- this will run later
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length); // this will call immediately
jetJSON請求是異步的,它在警報運行后完成。 如果你想要一個accruate警報,它應該在你的getJSON
回調中,如下所示:
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
});
alert(possibleMatches.length);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.