[英]How to listen for any 301/302 redirect status codes on cross-domain image requests?
我有几个<img>
链接(使用src
属性)到跨域URL,可能需要重定向到其他图像URL。 我需要以某种方式跟踪浏览器请求原始URL时发生的每个重定向。
例如,如果我有:
<img src='http://www.something.com/redirect'/>
并且http://www.something.com/redirect
向http://something.com/pic.jpg
发送了一个自定义location
标题,我需要了解它。 我如何在<img>
上检测JS或jQuery中的重定向?
我认为这不太可能(当然我不是专家,但那是AFAIK),至少不像人们想象的那么直截了当。
这是我认为尽可能接近您正在寻找的东西,我希望它能给您一些想法
var req = new XMLHttpRequest();
$('img').each(function() {
req.open('GET', $(this).prop('src'), false);
req.send(null);
alert(req.status);
});
两个不利方面:
<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>
如果您不受IE7约束,可以使用cors解决方案。 这将允许您在没有JSON-P限制的情况下请求跨域(即您可以获取状态代码)。
有关更多信息,请参阅https://developer.mozilla.org/en/http_access_control 。 对于简单的GET请求,您应该没问题,但如果您需要POST,则可能需要预检您的请求。
如何使用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加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.