最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to tell which ajax request failed? - Stack Overflow

programmeradmin2浏览0评论

I have this code block to post a HTTP request via jquery .post() method.

$.post("/product/update", formPostData)
.done(function (data) {
    // success
    alert(data.product_id + ' was updated!');
})
.fail(function (data) {
    // fail, but which request?
});

When it is successful it is easy to know which request we are dealing with, since the json returned by the server has the 'product_id' that I need.

But if it fails due to an error in which the server is not responsive, a connectivity problem for example, how can I tell which request has failed?

The data object has no clues because it only contains the server response.

How can I pass a value to the .fail() handler so I can determine which request has failed?

I have this code block to post a HTTP request via jquery .post() method.

$.post("/product/update", formPostData)
.done(function (data) {
    // success
    alert(data.product_id + ' was updated!');
})
.fail(function (data) {
    // fail, but which request?
});

When it is successful it is easy to know which request we are dealing with, since the json returned by the server has the 'product_id' that I need.

But if it fails due to an error in which the server is not responsive, a connectivity problem for example, how can I tell which request has failed?

The data object has no clues because it only contains the server response.

How can I pass a value to the .fail() handler so I can determine which request has failed?

Share Improve this question edited Mar 30, 2016 at 17:48 Ibrahim Khan 20.8k7 gold badges45 silver badges56 bronze badges asked Mar 30, 2016 at 17:47 Tony HTony H 3574 silver badges9 bronze badges 2
  • Do you mean that you are calling this multiple times with different values for formPostData and you don't know which call has failed? – LinuxDisciple Commented Mar 30, 2016 at 17:55
  • 2 What do you mean "which request failed"? You are only showing code for one request. If you hit the .fail() function, you know that it is the post that fail is connected to that failed. – Scott Marcus Commented Mar 30, 2016 at 17:55
Add a ment  | 

2 Answers 2

Reset to default 9

The this object is useful here. You should be able to parse this.data and get your post information from there:

.fail(function (jqXHR, textStatus, errorThrown) {
    console.log(this.data);
});

Another alternative would be write to the XHR object itself, and then it's there for you in the fail method, and wouldn't require you to use a closure:

var obj = { a: 1 };
var xhr = $.post("/product/update", obj)
   .done(function (data) {})
   .fail(function (jqXHR, textStatus, errorThrown) {
        console.log(this.data); // The raw string a=1 which was posted
        console.log(jqXHR.postData); // The {a: 1} javascript object
   });
xhr.postData = obj;
发布评论

评论列表(0)

  1. 暂无评论