Passing variables to $.ajax().done()

I'm lost. How might I pass a loop variable to an AJAX .done() call?

for (var i in obj) {
   $.ajax(/script/).done(function(data){ console.log(data); });
}

Obviously, if I were to do console.log(i+' '+data) i would return the very last key in the object obj on every single iteration. Documentation fails me.

Answers


You can use a closure (via a self executing function) to capture the value of i for each invocation of the loop like this:

for (var i in obj) {
    (function(index) {
        // you can use the variable "index" here instead of i
        $.ajax(/script/).done(function(data){ console.log(data); });
    })(i);
}

You can just create a custom field in the object that you send to $.ajax(), and it will be a field in "this" when the promise callback is made.

For example:

$.ajax( { url: "https://localhost/whatever.php", method: "POST", data: JSON.stringify( object ), custom: i // creating a custom field named "custom" } ).done( function(data, textStatus, jqXHR) { var index = this.custom; } );


Need Your Help

NoClassDefFoundError JsonAutoDetect while parsing JSON object

java eclipse json web-applications noclassdeffounderror

I am developing a webapp using Amazon's cloud services and I need to make use of JSON objects. How my project is set up is, I have an HTML form where the user will fill in their information and sub...

Suggestions for human editable data file format/parsing library

markup

For example, right now I have a roll-my-own solution that uses data files that include blocks like: