Capture redirect location of javascript XMLHttpRequest

后端 未结 2 878
忘掉有多难
忘掉有多难 2020-12-05 08:13

I know that you can\'t, when using an XMLHttpRequest, intercept a redirect or prevent it, as the browser will transparently follow it, but is it possible to either

A

相关标签:
2条回答
  • 2020-12-05 08:39

    1) Use different status code than 301 (2**) (if request by ajax) and handle redirection on client side:

    var STATUS = {
      REDIRECT: 280
    };
    
    $.post('/redirected', {}, function(response, status, request) {
      if (status == STATUS.REDIRECT) {
        // you need to return the redirect url
        location.href = response.redirectUrl;
      } else {
        $('#content').html(request.responseText);
      }
    });
    

    2) DO NOT REDIRECT:

    I use that in "redirect pattern" = redirecting after post request (you don't want to allow user to refresh the post request, etc..)

    With ajax request, this is not necessary, so when the post request is ajax, I do forward instead (just forward to different controller - depends on your server-side framework, or what you are using...). POST requests are not cached by browsers.

    Actually, I don't know what's the reason you need that, so this might not be so useful for you. This is helpful when server returns different responses for ajax requests than common requests, because when browser redirect ajax request, the redirected request is not XMLHttpRequest...

    [updated]

    You can access headers (of redirected request) like that:

    $.post('redirected', {}, function(r, s, req) {
      req.getAllResponseHeaders();
      req.getResponseHeader('Location');
    });
    

    There should be 'Location' header, but it depends on the server, which headers are sent back...

    0 讨论(0)
  • 2020-12-05 08:44

    After 4 years now it's possible to find the last redirect location using responseURL from XHR instance in Chrome 42+ (Opera 29+) and Firefox 39+ but it's not available in IE, Edge or safari yet.

    0 讨论(0)
提交回复
热议问题