jQuery $.get or $.post to catch page load error (eg. 404)

自闭症网瘾萝莉.ら 提交于 2019-11-28 07:35:25
Reigel

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

you could do

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

fail will be called if theres an error

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
});

Use $.ajax instead and use the error callback.

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

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/"})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!