How to catch a 400 response in jQuery getJSON call

假如想象 提交于 2019-12-23 08:00:59

问题


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.



来源:https://stackoverflow.com/questions/13373917/how-to-catch-a-400-response-in-jquery-getjson-call

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