如何在Ajax重定向后获取最终的URL? [英] How to get the final URL after an Ajax redirect?

查看:252
本文介绍了如何在Ajax重定向后获取最终的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on an AJAX script that makes a GET request to a shortened URL, like a bit.ly link. How do I actually get the URL of the final/redirected page?

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

I can get the response headers from the redirected page, but it doesn't appear to contain the URL information:

$.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请求。

I do not have control of the server making the get request.

推荐答案

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

As I answered a similar question here: https://stackoverflow.com/a/48445360/1398908

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

A better solution is to supply jQuery's ajax with a custom xhr object like this:

var xhr = new XMLHttpRequest();

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

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

Then you can access the current URL in any callback

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

这篇关于如何在Ajax重定向后获取最终的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆