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

前端 未结 2 1036
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 02:52

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


        
2条回答
  •  盖世英雄少女心
    2021-01-04 03:21

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

提交回复
热议问题