小编Cal*_*hus的帖子

有没有办法将变量从beforeSend传递给jQuery .ajax函数中的成功函数?

问题

当使用AJAX查询远程API时,由于请求的异步特性,它在完成时都会返回。问题是,当我不得不使用不同的条件对相同的API进行迭代调用时,我不知道会返回哪个响应。

问题:是否可以从中传递变量

示例代码:(简体)

n=5;
for(i=0; i < n; i++) {
  $.ajax({
    url: someURL,
    method: post,
    // I don't want to have to use async: false, that's bad
    // async: false,
    data: JSON.stringify(someData),
    beforeSend: function(){
      console.log("Starting request #"+i)
    },
    error: function(err, code, text) {
      alert("Something went wrong: \n\n" + code + ": " + text);
    },
    success: function(response) {
      console.log("Response for request #"+i)
      console.log(response)
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

问题在于最终的成功功能:我应该看到的是:

Starting request #0
Starting request #1
Starting request #2
Starting request #3 …
Run Code Online (Sandbox Code Playgroud)

ajax jquery

3
推荐指数
1
解决办法
946
查看次数

标签 统计

ajax ×1

jquery ×1