How do I pass a variable inside of an ajax call wh

2019-07-22 20:23发布

问题:

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

});

回答1:

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

Also here, example #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:

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.

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.

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?

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