gpt4 book ai didi

javascript - 如何在 for 循环(javascript)内的 ajax 调用内传递变量?

转载 作者:行者123 更新时间:2023-11-30 13:20:26 25 4
gpt4 key购买 nike

使用 api,我需要第一个响应和第二个响应之一才能提供新页面。我面临的问题是我的变量 $x 总是设置为循环中最后一个 # 的值,即在这个特定情况下为 103。这是我的代码:

$.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 调用嵌套在另一个功能范围内(感谢 Matt 的更正)将解决意外行为。我已经被这个烧毁了Object creation in loop broken; unrolled works

同样在这里,示例 #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);
}

关于javascript - 如何在 for 循环(javascript)内的 ajax 调用内传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com