如何在 jquery 中获取 406 错误(不可接受)

2024-04-17

我正在 my.js 中进行错误处理,其中我对其他服务器进行跨域调用,对于动态 HTML 模板,我正在使用 Mustache.js。

$.getJSON(url, function(data, textStatus, xhr) {
  $.each(data, function(i, data) {
    introPage(data);
  });
}).fail(function(Error) {
        alert(Error.status);
}); 

function introPage(data )
{
    $.getJSON('myphp.php?jsoncallback=?&template='+testTemplate, function(msg) {
        // my operations

    }).error(function(data) {
            }); 
}

我们在 getJSON 中有 .fail() 来捕获错误getJSON http://api.jquery.com/jQuery.getJSON/。我能够捕获 404 错误(未找到),但是当涉及 406 错误(不可接受或说无效输入)或 401 错误(未经授权的访问)时,.fail() 似乎不起作用

but throws the error in console JSON ERROR IN CONSOLE

当我点击链接时也是如此。它以下面的格式显示 jquery 回调中的错误

jQuery191014790988666936755_1378113963780({
  "error": {
    "code": 406,
    "message": "Not Acceptable: Sorry, There are no results to display for the given input."
  }
});

现在我想知道如何在我的 JS 中得到这个错误。我没有收到错误代码 406 和 401。我需要该错误代码以便显示适当的错误页面。

谢谢


判断通过jsoncallback=?参数和响应jQuery191...780({...}),看起来 jQuery 正在生成 JSONP 请求。 JSONP请求不受同源策略限制,但有以下限制如此处所述 http://api.jquery.com/jQuery.ajax/:

注意:跨域脚本不会调用此[错误]处理程序,并且 跨域 JSONP 请求。

解决方案:

  1. 如果服务器允许跨域请求,则创建纯JSON请求
  2. Look at answers for these questions:
    • 使用 JSONP 时如何捕获 jQuery $.getJSON [...] 错误? https://stackoverflow.com/q/309953/87015
    • jQuery ajax (jsonp) 忽略超时并且不触发错误事件 https://stackoverflow.com/q/1002367/87015
  3. Use jquery-jsonp https://github.com/jaubourg/jquery-jsonp-- 它不会给你 HTTP 错误代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 jquery 中获取 406 错误(不可接受) 的相关文章

随机推荐