In an AJAX call, 302 is not followed

后端 未结 4 2112
孤独总比滥情好
孤独总比滥情好 2020-12-28 15:23

I\'m using jQuery 1.6.2 to make a POST AJAX request to a page on the same domain. That page does a 302 redirect to another page.

Now, on my local machine this work f

相关标签:
4条回答
  • 2020-12-28 16:01
    function doAjaxCall() {
       $.ajaxSetup({complete: onRequestCompleted});
       $.get(yourUrl,yourData,yourCallback);
    }
    
    function onRequestCompleted(xhr,textStatus) {
       if (xhr.status == 302) {
          location.href = xhr.getResponseHeader("Location");
       }
    }
    

    following questions related to your answer. you can find the answer from below links.

    Catching 302 FOUND in JavaScript

    How to manage a redirect request after a jQuery Ajax call

    0 讨论(0)
  • 2020-12-28 16:04

    Based on this answer: https://stackoverflow.com/a/8752354/698289 I found the following code to be very useful:

    $('body').ajaxComplete(function (e, xhr, settings) {
        if (xhr.status == 200) {
            var redirect = null;
            try {
                redirect = $.parseJSON(xhr.responseText).redirect;
                if (redirect) {
                    window.location.href = redirect;
                }
            } catch (e) {
                return;
            }
        }
    });
    

    Then you just provide JSON such as the following:

    {redirect: '/redirect/to/this/path'}
    

    And the ajaxComplete will make sure to redirect the browser.

    Be mindful that $.ajax('complete') triggers AFTER $.ajax('success') or $.ajax('error')

    0 讨论(0)
  • 2020-12-28 16:14

    I consider this to be a server-side issue, and not client-side. The browser is correct not to follow redirections to http when it makes ajax request by https, as that would be a security flaw.

    I realized I was using relative paths, such as HttpResponseRedirect('/path/to/'). On some layer, that url was prepended with the http:// prefix and that was what the browser received: http://example.com/path/to/

    You must ensure that the Location gets sent in the response header with a full path, including the https://.

    0 讨论(0)
  • 2020-12-28 16:16

    Turns out a bug in the redirect code caused the redirect to go to http:// while the page that was requested was https://. That makes the browser refuse to follow the redirect.

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