开发者

How do I associate an Ajax error result with the original request?

开发者 https://www.devze.com 2023-01-29 13:20 出处:网络
I am sending data to the server in small bursts using the jQuery ajax function.Each chunk of data is a simple key-value map (the data property passed to the ajax function).

I am sending data to the server in small bursts using the jQuery ajax function. Each chunk of data is a simple key-value map (the data property passed to the ajax function).

If a request fails, how can my error event handler identify which specific set of data failed to be uploaded?

The function signature of the jQuery error handler is:

error(XMLHttpRequest, textStatus, er开发者_StackOverflowrorThrown)

Neither textStatus or errorThrown seem useful to identify the failed set of data, and the XHR doesn't seem to offer that capability either.

Simply put, if a request fails, I want to be able to get the id property of the data that I passed to the ajax function. How can I do this?


Check this... From the docs - pay attention to the highlighted section:

The beforeSend, error, dataFilter, success and complete options all take callback functions that are invoked at the appropriate times. The this object for all of them will be the object in the context property passed to $.ajax in the settings; if that was not specified it will be a reference to the Ajax settings themselves.

So, in the error() callback (also success and complete, etc), this will be the object passed to $.ajax() - unless you are using the context parameter to change it.

As a note, the data param passed into $.ajax() will be converted to a serialized string for a GET or POST request

The other option, is to just make sure your error() callback has access to the variable in the same scope:

 (function() { 
   // create a scope for us to store the data:
   var data = {id: 1};
   $.ajax({
      url: '/something-to-genereate-error',
      data: data,
      error: function() {
        console.log(this, data);
      }
   });
 })(); // call the function immediatey

See this fiddle for an example - Note that the data inside of this is "id=1" wereas the data we held a copy of is still {id:1}

Also - Note that the closure here ((function() { .... })()) Is pretty much unnecessary, it is just showing a way to store the data variable before passing it into $.ajax() and the using it in the callback. Most likely this ajax call already lies within a function where you could do this.


Ok, I think I found it (based on my previous answer and the one from gnarf,

$.ajax({
    type: "POST",
    url: "not-found",        
    context: {id: 123, name: "hello world"},        
    error: function(){  
        console.debug($(this)); //only works in chrome                    
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号