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

时间:2022-08-26 11:15:29

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:

使用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');
}

});

});

2 个解决方案

#1


3  

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

我的直觉是,将Ajax调用嵌套在另一个功能范围内(感谢Matt)将解决意外行为。我被这个已经在循环中创建的对象破坏了;展开工作

Also here, example #5: http://www.javascriptkit.com/javatutors/closures2.shtml

在这里,示例#5:http://www.javascriptkit.com/javatutors/closures2.shtml。

Following the pattern given by Engineer,

按照工程师给出的模式,

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);
}

#2


0  

What you're experiencing is closure. When the loop spins round, the value for $x is updated. However, when the ajax function comes to grab it - it's using a reference. So as you find, you end up with the last value.

你正在经历的是结束。当循环旋转时,将更新$x的值。然而,当ajax函数抓取它时——它使用的是引用。结果是最后一个值。

Try and think more functional? What are you trying to do? Let's say you're trying to postMessage - wrap that in a function and pass in the message.

试着思考更多功能?你想做什么?假设您正在尝试postMessage—将其封装到一个函数中并传递消息。

Your code will become easier to read, and you won't get your variables mangled.

您的代码将变得更容易阅读,并且您不会使您的变量损坏。

I was about to throw out some code, but noticed something I wanted to clarify - you're using the index in both loops to get a single message from a messages array, yet the POST to testapi.php seems to be working on a single message? What kind of response is expected from that?

我正要抛出一些代码,但注意到有一件事我想澄清——您正在两个循环中使用索引从消息数组中获取一条消息,但是要向testapi发布消息。php似乎只处理一条消息?预计会有什么样的反应呢?

 Update: Created jsFiddle to Demo Problem

Here you go here's some code to help you out.

这里有一些代码可以帮助你。

    function correctOutputPlox(id) {
     setTimeout(function() {
       $("#output").append("<li>" + id + "</li>");
     }, 500);   
    }

    function runNicely() {
        // same loop...
        for (var x = 0; x < 10; x++) {
            // but rather than use 'x' (which is going to change, we pass it's value into a function which doesn't have access to the original 'x' since it's in a different lexical scope.
            correctOutputPlox(x);
        }
    }

    function showProblem() {
        for (var x = 0; x < 10; x++) {
            setTimeout(function() {
                $("#output").append("<li>" + x + "</li>");
            }, 500);
        }
    }

    showProblem();
    runNicely();

#1


3  

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

我的直觉是,将Ajax调用嵌套在另一个功能范围内(感谢Matt)将解决意外行为。我被这个已经在循环中创建的对象破坏了;展开工作

Also here, example #5: http://www.javascriptkit.com/javatutors/closures2.shtml

在这里,示例#5:http://www.javascriptkit.com/javatutors/closures2.shtml。

Following the pattern given by Engineer,

按照工程师给出的模式,

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);
}

#2


0  

What you're experiencing is closure. When the loop spins round, the value for $x is updated. However, when the ajax function comes to grab it - it's using a reference. So as you find, you end up with the last value.

你正在经历的是结束。当循环旋转时,将更新$x的值。然而,当ajax函数抓取它时——它使用的是引用。结果是最后一个值。

Try and think more functional? What are you trying to do? Let's say you're trying to postMessage - wrap that in a function and pass in the message.

试着思考更多功能?你想做什么?假设您正在尝试postMessage—将其封装到一个函数中并传递消息。

Your code will become easier to read, and you won't get your variables mangled.

您的代码将变得更容易阅读,并且您不会使您的变量损坏。

I was about to throw out some code, but noticed something I wanted to clarify - you're using the index in both loops to get a single message from a messages array, yet the POST to testapi.php seems to be working on a single message? What kind of response is expected from that?

我正要抛出一些代码,但注意到有一件事我想澄清——您正在两个循环中使用索引从消息数组中获取一条消息,但是要向testapi发布消息。php似乎只处理一条消息?预计会有什么样的反应呢?

 Update: Created jsFiddle to Demo Problem

Here you go here's some code to help you out.

这里有一些代码可以帮助你。

    function correctOutputPlox(id) {
     setTimeout(function() {
       $("#output").append("<li>" + id + "</li>");
     }, 500);   
    }

    function runNicely() {
        // same loop...
        for (var x = 0; x < 10; x++) {
            // but rather than use 'x' (which is going to change, we pass it's value into a function which doesn't have access to the original 'x' since it's in a different lexical scope.
            correctOutputPlox(x);
        }
    }

    function showProblem() {
        for (var x = 0; x < 10; x++) {
            setTimeout(function() {
                $("#output").append("<li>" + x + "</li>");
            }, 500);
        }
    }

    showProblem();
    runNicely();