访问帖子请求's成功/完成/错误函数中的参数数据

Access to the post request's argument data in succeed/complete/error functions

本文关键字:错误 完成 函数 数据 参数 成功 请求 访问      更新时间:2023-09-26

我有一堆jQuery AJAX发布请求封装在for循环中。每个请求都提供不同的参数。我的问题是,如果请求失败,如何判断该请求传递了哪些参数数据?

当我尝试时:

for(i = 0; i < toSubmit.length; i++) {
  $.post('doSomething.php',
         {id: toSubmit[i]},
         function(data) { /* Do something here */ },
         'json')
  .error(function() {
    console.log(toSubmit[i] + " didn't work!");
  });
}

error函数将只输出toSubmit中的最后一个值,因为i指针一直在for循环中前进,而请求是异步触发的。同样的事情发生在successcomplete函数中;我解决这个问题的方法是确保返回的JSON包含相应的id;但是如果请求失败,我就不能使用这种变通方法。

有没有办法让我了解这些信息,或者有没有更好的方法来拒绝这些请求?

似乎必须为方法调用设置正确的上下文。您可以查看jQueryproxy()方法,该方法允许您为回调提供正确的上下文。

试试这样的东西:

for(i = 0; i < toSubmit.length; i++) {
  var ctx = {id: i};
  $.post('doSomething.php',
         {id: toSubmit[i]},
         function(data) { /* Do something here */ },
         'json')
  .error( $.proxy(function() {
    console.log(this.id + " didn't work!");
  }, ctx) );
}​

试试这个:

beforeSend:function(jqXHR, settings){
   jqXHR.parameters = { /* data or parameters store here*/}
}

error: function(jqXHR, textStatus, errorThrown){
   var params = jqXHR.parameters
}