16

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

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

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

4

2 回答 2

20

您可以在发送到 $.ajax() 的对象中创建一个自定义字段,并且this在进行 promise 回调时它将是一个字段。

例如:

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

于 2016-11-01T03:28:24.047 回答
15

您可以使用闭包(通过自执行函数)来捕获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);
}
于 2012-04-07T23:39:48.933 回答