Is it possible to get page redirect information via Ajax?

前端 未结 5 949
眼角桃花
眼角桃花 2021-02-19 19:27

Without ajax, if we load http://example.com/1 and if it redirects to http://example.com/2 then the browser gets appropriate headers and the Browser URL

5条回答
  •  死守一世寂寞
    2021-02-19 19:56

    As the already mentioned responseURL doesn't have the best browser support yet, there are 2 more alternative for this case that could be used, http request headers and cookies.

    The benefit with these is they don't interfere with the content itself, like for example query string keys, hash tags or embedded in the response data.


    Request headers

    Server side

    • PHP

      $req->addHeader("X-Response-Url", "....");
      
    • ASP

      headers.Add("X-Response-Url", "....");
      

    Client side

    xhr.onreadystatechange = function(e) {
      if (xhr.status == 200 && xhr.readyState == 4) {
    
        var resp_url = xhr.getResponseHeader("X-Response-Url");
    
        if (send_url != resp_url) {
          // redirected
        }
    
      }
    }
    

    Cookies

    • PHP

      setcookie("XResponseUrl", "...");
      
    • ASP

      Response.Cookies("XResponseUrl") = "..."
      

    Client side

    xhr.onreadystatechange = function(e) {
      if (xhr.status == 200 && xhr.readyState == 4) {
    
        var resp_url = getCookie("XResponseUrl");
    
        if (send_url != resp_url) {
          // redirected
        }
    
      }
    }
    
    
    function getCookie(name) {
      var re = new RegExp(name + "=([^;]+)");
      var value = re.exec(document.cookie);
      return (value != null) ? unescape(value[1]) : null;
    }
    

提交回复
热议问题