我迷路了。如何将循环变量传递给 AJAX .done() 调用?
for (var i in obj) {
$.ajax(/script/).done(function(data){ console.log(data); });
}
显然,如果我这样做,console.log(i+' '+data)
我obj
会在每次迭代时返回对象中的最后一个键。文档让我失望。
您可以在发送到 $.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; } );
您可以使用闭包(通过自执行函数)来捕获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);
}