javascript 如何在 jQuery getJSON 调用中捕获 400 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13373917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:35:44  来源:igfitidea点击:

How to catch a 400 response in jQuery getJSON call

javascriptjqueryajaxjsonhttp-status-code-400

提问by Muhammad Usman

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()?

在 jQuery 中,我想使用该$.getJSON()方法从 Facebook 获取一些数据,但如果令牌无效,Facebook 将返回 400 状态。我如何才能捕获错误$.getJSON()而不是$.ajax()

回答by Elby

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

回答by A.M. D.

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

jquery Ajax 文档提供了两种解决方案,第一种是错误函数:

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

回答by Varun Achar

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

使用complete(jqXHR, textStatus)函数回调并调查响应并向用户显示适当的消息。