jQuery $.get or $.post to catch page load error (e

2019-01-17 16:51发布

How do you catch Server Error or 404 page not found, when you use $.get or $.post ?

For example:

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
});

That will do absolutely nothing if there is a Server Error loading "/myhandler", or if it is not found.

How do you make it notify you if there is an error?

标签: jquery post get
5条回答
不美不萌又怎样
2楼-- · 2019-01-17 16:57

The other answers are nice and all, but there's alternative solutions, namely .ajaxSetup, .ajaxError and other Ajax event handlers (check the ajaxSetup doc page for more info on the rest).

For example, with .ajaxError you can setup a global handler of all your ajax errors from .post, .get, .getJSON and .ajax for a specific set of elements.

$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) {
    // handle ajax error here
});
查看更多
Deceive 欺骗
3楼-- · 2019-01-17 17:05

Use $.ajax instead and use the error callback.

http://api.jquery.com/jQuery.ajax/

查看更多
We Are One
4楼-- · 2019-01-17 17:11

use error handler on $.ajax()

$.ajax({
    url: "/myhandler", 
    data: {value: 1},
    type: 'post',
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
    },
    success: function(data){}
});

demo

查看更多
干净又极端
5楼-- · 2019-01-17 17:12

you could do

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
}).fail(function(){ 
  // Handle error here
});

fail will be called if theres an error

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-17 17:13

Try using $.ajaxSetup() , stausCode option

$.ajaxSetup({
   statusCode : {
     // called on `$.get()` , `$.post()`, `$.ajax()`
     // when response status code is `404`
     404 : function (jqxhr, textStatus, errorThrown) {
             console.log(textStatus, errorThrown);
           }
     }
 });

// $.get("/path/to/url/");
// $.post("/path/to/url/");
// $.ajax({url:"/path/to/url/"})
查看更多
登录 后发表回答