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

Need Your Help

PHP Downloading a file from a different password protected server

php download

I am building an application that will allow users to download some pdf files, but these files are stored on a different server which is password protected, the password is known.

Get and Display Title of Element

jquery

I have several images on a page, all in list items. On hover of one of those images, I would like to get the title attribute and display it in a div. Here's my code so far:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.