我有一個數組,其中包含Web服務的兩個URL。以下代碼正確執行這兩個帖子並將正確的數據輸出到屏幕。然而,有趣的是,該功能將只打印"2"
到控制檯,但它正確地打印出對象的正確數目每個請求,屏幕保護蓋: 使用異步代碼的循環中的JavaScript關閉
你可以看到有不同數量從每個AJAX請求返回的對象。
$(document).ready(function() {
var urlList = ['../NewService.asmx/GetNames', '../NewService.asmx/GetPersons'];
//executes both functions
multipleAjaxCalls(urlList);
//ajax function definition
function multipleAjaxCalls(array) {
var functionArray = [];
for (var i = 0; i < array.length; i++) {
var func = (function() {
$.ajax({
type: "POST",
url: array[i],
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log('this is the index: ' + i);
console.log('ajax success ' + i);
console.log(data.d);
},
error: function (xhr) {
console.log(xhr.status);
}
})
})(i); //<--I honestly don't understand what passing paramters to these closing parens actually does
//in this case it doesn't affect the output
functionArray.push(func);
}
return functionArray //this is superfluous
}
});
爲什麼這個函數返回正確這兩組數據,但只打印出的"2"
的指標,特別是當陣列具有兩個長度是多少?
*「我真的不明白什麼傳遞參數給這些關閉的參數實際上「*您正在調用一個函數並將參數傳遞給它。想象一下你有一個函數'foo'。然後在'foo(i)'中,你調用'foo'並傳遞'i'作爲參數。這就是你在這裏做的。唯一不同的是,您沒有對該功能的引用,您正在定義並「在現場」調用該功能。它沒有任何意義,因爲如前所述,你沒有定義函數來期望*參數。 –
@FelixKling英雄:) – wootscootinboogie