Catching 302 FOUND in JavaScript

一世执手 提交于 2019-11-26 20:06:36
Steg

The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:

How to manage a redirect request after a jQuery Ajax call

However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON. In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.

Elias Zamaria

I don't think so. The W3C says that HTTP redirects with certain status codes, including 302, must be transparently followed. Quoted below:

If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it MUST be transparently followed (unless it violates security or infinite loop precautions). Any other error (including a 401) MUST cause the object to use that error page as the response.

As an experiment, I tried doing Ajax requests from various browsers (Firefox 3.5, Chrome, IE8, IE7, IE6) to a server giving a 302 status code, and showing the status in the browser's request object. In every case, it showed up as 200.

In my problem reason was:

i was using localhost/Home/Test addres for testing the page. But ajax request code using 127.0.0.1/Home/AjaxRequest for url parameter. When the urls are different this error occurs.

maybe it helps someone :)

Rather than asking the Javascript code to Handle 302, it would be better to return a 500 with custom error code+ message on event of 302

function doAjaxCall() {
   $.ajaxSetup({complete: onRequestCompleted});
   $.get(yourUrl,yourData,yourCallback);
}

function onRequestCompleted(xhr,textStatus) {
   if (xhr.status == 302) {
      location.href = xhr.getResponseHeader("Location");
   }
}

The best solve is:

set the variable with a attribute of any object example

<html>
·
·
     <span url="http://www.google.com"></span>
·
·
</html>

$('.example').on('click', function(){
     $url = $(this).attr('url');

     $.get($url, function(data){ alert(data); })
})

If the url is seted directly in the js, You will should find a error 302, I don't know because reason occur this error, but if you get the url of a attribute, this error not ocurre

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