将变量传递给$ .ajax().done()

Phi*_*une 13 ajax jquery loops promise

我迷路了.我如何将循环变量传递给AJAX .done()调用?

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

显然,如果我这样做,console.log(i+' '+data) obj在每次迭代时返回对象中的最后一个键.文档让我失望.

Dar*_*ola 15

您可以在发送到$ .ajax()的对象中创建自定义字段,并在进行promise回调时将其作为"this"中的字段.

例如:

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


jfr*_*d00 13

您可以使用闭包(通过自执行函数)捕获i循环的每次调用的值,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)