如何侦听跨域映像请求上的任何301/302重定向状态代码

How to listen for any 301/302 redirect status codes on cross-domain image requests?

本文关键字:重定向 代码 状态 任何 何侦听 映像 请求      更新时间:2024-02-18

我有一些<img>链接到跨域URLS(具有src属性),可能需要重定向到其他图像URL。我需要以某种方式跟踪浏览器请求原始URL时发生的每一次重定向。

例如,如果我有:

<img src='http://www.something.com/redirect'/>

http://www.something.com/redirecthttp://something.com/pic.jpg发送了一个自定义的location头,我需要了解它。我如何在<img>上检测JS或jQuery中的重定向?

如果您不受IE7的限制,您可以使用cors解决方案。这将允许您在没有JSON-P限制的情况下请求跨域(即,您可以获得状态代码)。

请参阅https://developer.mozilla.org/en/http_access_control了解更多信息。对于一个简单的GET请求,你应该可以,但如果你需要POST,那么你可能需要预先处理你的请求。

我认为这不太可能(当然我不是专家,但这是AFAIK),至少不像人们想象的那样直截了当。

以下是我认为最接近你想要的东西,我希望它能给你一些想法

var req = new XMLHttpRequest();
$('img').each(function() {
    req.open('GET', $(this).prop('src'), false);
    req.send(null);
    alert(req.status);
});

两面:

  1. 仅适用于同一域上的图像
  2. 您必须请求两次图像(或者您可以先请求,然后使用结果显示图像)
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<img id='img' src='' width='200' />
<script type='text/javascript'>
/* our image */
var image =  new Image();
$(image).load('yourimage.png', function(response, status, xhr) {
    if (xhr.status == 200) {
        // image loaded, now display the image
        $('#img').attr('src','yourimage.png')
    } else {
        alert(xhr.status);
    }
});
</script>

如何使用Ajax加载图像,未经测试的伪代码如下:

HTML:

<img id="img1" src="blank.gif">

JQuery:

GetImage("http://www.something.com/redirect");
function GetImage(url)
{
    $.ajax({
        type: "GET",
        url: url,
        success: function(data, textStatus) {
            if (data.redirect) {
                // data.redirect contains the string URL to redirect to
                ProcessLocationHeader(data);
                GetImage(data.redirect);
            }
            else {
                // No redirect means we have the correct image
                $("#img1").src = url;
            }
        }
    });
}

由于浏览器会缓存图像,因此不会从服务器twize加载。