-->

How to catch a 400 response in jQuery getJSON call

2019-06-22 17:17发布

问题:

In jQuery I want to fetch some data from facebook using the $.getJSON() method, but if the token is invalid, Facebook is returning the 400 status. How I can catch the error in $.getJSON() instead of $.ajax()?

回答1:

I think this will work for you

$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("success 2"); })
.error(function() { alert("error occurred "); })
.complete(function() { alert("Done"); });


回答2:

The jquery Ajax docs offer two solutions, the first is the error function:

    error(jqXHR, textStatus, errorThrown)

which detects and reports textual portions of error messages for you, the other is the status code feature (on the same page). Here's the example usage from that page:

    $.ajax({
      statusCode: {
        404: function() {
          alert("page not found");
        }
      }
    });


回答3:

Use the complete(jqXHR, textStatus) function callback and investigate the response and show the approprite message to the user.