我如何通过Ajax调用内的一个变量,它是一个内循环(JavaScript的)? [英] How do I pass a variable inside of an ajax call which is inside of a for loop (javascript)?
问题描述
使用一个API,我需要的第一个响应的一个与一起以服务了新的一页,第二反应。我现在面临的问题是,我的变量$ x被始终设置为任何的最后#处于环路,即103在此特定情况。这是我的code:
Working with an api and I need to one of the first responses alongside with the second response in order to serve up a new page. The problem I'm facing is that my variable $x is always set to whatever the last # is in the loop, ie 103 in this specific case. Here is my code:
$.ajax({
dataType: 'text',
type: 'post',
url: 'getAllMessages.php',
success: function(responseData) {
var newString = responseData;
var newerString = newString.substring(0, newString.length - 1);
$newObject = jQuery.parseJSON(newerString);
//console.log($newObject);
for($x = 0; $x < $newObject.messages.length; $x++){
$.ajax({
data: {clientFolderId: $newObject.messages[$x].clientFolderId, messageId: $newObject.messages[$x].messageId},
dataType: 'text',
type: 'post',
url: 'testapi.php',
success: function(responseData2){
//alert($x);
var newString2 = responseData2;
var newerString2 = newString2.substring(0, newString2.length - 1);
$newObject2 = jQuery.parseJSON(newerString2);
if($newObject2.statistics.delivered > 1000){
console.log($newObject.messages[$x]);
console.log($newObject2);
}
},
error: function(responseData2){
alert('failure in testapi.php');
}
});
}
},
error: function(responseData) {
alert('failure in getAllMessages.php');
}
});
推荐答案
我的直觉说嵌套在另一个功能范围的Ajax调用(修正感谢马特)将解决意外的行为。我被烧毁,这已经<一个href="http://stackoverflow.com/questions/10095371/object-creation-in-loop-broken-unrolled-works">Object创造循环破裂;展开工程
My intuition says nesting the Ajax call inside another functional scope (correction thanks to Matt) will resolve the unexpected behavior. I got burned by this already Object creation in loop broken; unrolled works
另外这里,例如#5: http://www.javascriptkit.com/javatutors/closures2的.shtml
Also here, example #5: http://www.javascriptkit.com/javatutors/closures2.shtml
继工程师给出的模式,
for($x = 0; $x < $newObject.messages.length; $x++){
(function($x) {
$.ajax({
data: {clientFolderId: $newObject.messages[$x].clientFolderId, messageId: $newObject.messages[$x].messageId},
dataType: 'text',
type: 'post',
url: 'testapi.php',
success: function(responseData2){
alert($x);
var newString2 = responseData2;
var newerString2 = newString2.substring(0, newString2.length - 1);
$newObject2 = jQuery.parseJSON(newerString2);
if($newObject2.statistics.delivered > 1000){
console.log($newObject.messages[1]);
console.log($newObject2);
}
},
error: function(responseData2){
alert('failure in testapi.php');
}
});
})($x);
}
这篇关于我如何通过Ajax调用内的一个变量,它是一个内循环(JavaScript的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!