如何在Ajax重定向后获取最终的URL?

时间:2015-06-23 03:38:50

标签: jquery ajax

我正在研究一个AJAX脚本,该脚本向缩短的URL发出GET请求,就像bit.ly链接一样。如何实际获取最终/重定向页面的URL?

我可以从重定向的页面获取响应标头,但它似乎不包含URL信息:

$.ajax({
  url: "http://www.thislinkredirects.com",
  success: function(data, status, xhr) {
    var response = $(data);
  },
  complete: function(xhr) {
    console.log(xhr.getAllResponseHeaders());
  }
});

结果:

Date: Tue, 23 Jun 2015 03:22:07 GMT
Allow: POST, GET, OPTIONS, PUT, DELETE
Server: lighttpd/1.4.35
X-Powered-By: PHP/5.3.3
Transfer-Encoding: chunked
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Content-type: text/html
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: accept, authorization

我无法控制发出get请求的服务器。

4 个答案:

答案 0 :(得分:5)

我在这里回答了类似的问题:https://stackoverflow.com/a/48445360/1398908

更好的解决方案是使用这样的自定义xhr对象提供jQuery的ajax:

var xhr = new XMLHttpRequest();

$.ajax({
    url: '/url',
    type: 'post',
    data: '...',
    xhr: function() {
         return xhr;
    }
});

然后您可以在任何回调中访问当前网址

success: function () {
    console.log(xhr.responseURL);
}

答案 1 :(得分:0)

尝试将Location:传递给ajaxComplete,然后阅读标题。

标题应显示{{1}}字段。

答案 2 :(得分:0)

试试这段代码......

$.ajax({
  url: "https://instagram.com/oauth/authorize/?client_id=e40f15a90**c89851d8a66&redirect_uri=http://examle.com&response_type=token",
  success:function(result,status,xhr){
    console.log(xhr.getResponseHeader('Location'));<---NULL
  }
});

答案 3 :(得分:0)

幸运的是,我有一个规范的标签:

var matches = xhr.responseText.match(/<link rel="canonical" href="([^"]+)"\/>/);
var url = matches[1];

相关问题