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

后端 未结 5 1307
予麋鹿
予麋鹿 2020-12-09 04:06

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)          


        
相关标签:
5条回答
  • 2020-12-09 04:39

    you could do

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

    fail will be called if theres an error

    0 讨论(0)
  • 2020-12-09 04:51

    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/"})
    
    0 讨论(0)
  • 2020-12-09 04:59

    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
    });
    
    0 讨论(0)
  • 2020-12-09 05:02

    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

    0 讨论(0)
  • 2020-12-09 05:03

    Use $.ajax instead and use the error callback.

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

    0 讨论(0)
提交回复
热议问题