How to get 406 Error (not acceptable) in jquery

只谈情不闲聊 提交于 2019-12-04 06:32:18

问题


I am doing error handling in my.js, where i am having cross domain call to other server, also for dynamic HTML template i am using 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) {
            }); 
}

We have .fail() in getJSON to catch the errors in getJSON. I am able to catch 404 error (not found) but when it comes to 406 error (not acceptable or say invalid input) or 401 error(unauthorised access), .fail() does not seems to work

but throws the error in console

Also when i click the link. it shows error in jquery callback in below format

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

Now i am wondering how to get this error in my JS . i am not getting Error code 406 and 401.I need that error code so that appropriate error page be displayed.

Thank you


回答1:


Judging by the jsoncallback=? parameter and the response jQuery191...780({...}), it seems like jQuery is generating a JSONP request. JSONP requests are not subject to the same origin policy restrictions but they do have the following limitation as described here:

Note: This [error] handler is not called for cross-domain script and cross-domain JSONP requests.

The solution:

  1. Create a pure JSON request if the server allows cross-domain requests
  2. Look at answers for these questions:
    • How do I catch jQuery $.getJSON [...] error when using JSONP?
    • jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event
  3. Use jquery-jsonp -- it does not give you the HTTP error code


来源:https://stackoverflow.com/questions/18570486/how-to-get-406-error-not-acceptable-in-jquery

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