这是因为您有一个 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.
}