[英]How to change console.log() output message depending on if variable is defined or not
[英]Why does moving the console.log() for a variable into a second AJAX call change the output?
我不確定將console.log()移入第二個AJAX調用時,為什么我的代碼輸出會更改。
通過在兩個AJAX調用之間拆分三個console.logs,此代碼返回我想要的內容(所有productTitles及其productURL和numProductTopics):
但是,在將所有三個console.logs移動到第二個AJAX調用之后,此代碼每次都使用相同的期望numProductTopics返回相同的productTitle和productURL:
有人可以解釋一下嗎?
這是因為您有一個for循環,可在其中為變量分配值並啟動ajax調用,該調用將在執行ajax成功回調之前執行。 因此,它們將保留最后一次迭代的值。
for (var i=0;i < results.data.length; i++) {
var object = results.data[i];
if (object.canonical_name && object.name) {
var productTitle = object.name;
productURL = "getsatisfaction.com/trinet/products/" + object.canonical_name;
jQuery.ajax({
type: 'GET',
url: apiBaseURL + 'topics.json?product=' + object.canonical_name,
dataType: 'jsonp',
success: function(results2) {
var numProductTopics = results2.total;
console.log(productTitle); //<-- this will have the value from last iteration
console.log(productURL);//<-- this will have the value from last iteration
console.log(numProductTopics);
}
});
}
您也可以通過將每個循環的變量封裝在ajax調用中(通過將其作為函數調用)來解決它。 從根本上講,您希望將變量鎖定為每次迭代的閉合變量。
for (var i=0;i < results.data.length; i++) {
var object = results.data[i];
if (object.canonical_name && object.name) {
var productTitle = object.name;
productURL = "getsatisfaction.com/trinet/products/" + object.canonical_name;
(function(productTitle, productURL){ //<-- Take the arguments
jQuery.ajax({
type: 'GET',
url: apiBaseURL + 'topics.json?product=' + object.canonical_name,
dataType: 'jsonp',
success: function(results2) {
var numProductTopics = results2.total;
console.log(productTitle);
console.log(productURL);
console.log(numProductTopics);
}
});
})(productTitle, productURL); //Lock in the variables here invoking the function call.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.