【发布时间】:2011-03-24 15:39:58
【问题描述】:
我正在使用 Twitter avatar API 在客户端获取用户的头像 URL,我想缓存响应,但不是常规的 JSON(或者实际上是任何其他类型),它们只是发出 302 重定向。
这不起作用(因为它是跨域的):
jQuery.getJSON('https://api.twitter.com/1/users/profile_image/60173.json',
function(data, status, jqxhr){
console.log("data: ", data);
console.log("status: ", status);
console.log("jqxhr: ", jqxhr);
console.log(jqxhr.getResponseHeader('Location'));
console.log(jqxhr.getAllResponseHeaders());
})
数据为空,状态为“成功”,jqhxr 返回一个 jqxhr 对象,但 getResponseHeader() 和 getResponseHeaders() 为空,因为它是跨域调用,而不是真正的 XMLHTTP 调用。
所以我想我可以在 302 发生后使用 load() 事件来显示图像的实际 url。我试过这个:
function avatar_loaded(img) {
console.log("We loaded an avatar for %s (img)[0].src is %o
attr('src') is %o getAttribute('src') is %o", img, jQuery(img)[0].src, jQuery(img).attr('src'), img.getAttribute("src"));
}
var avatar_url = "https://api.twitter.com/1/users/profile_image/60173";
jQuery('body').append("<img onload='avatar_loaded(this)' src='" +
avatar_url + "' width='0' height='0'>");
您会看到 avatar_loaded 函数被调用了两次。一次使用初始 img src (https://api.twitter.com/1/users/profile_image/60173),然后再次使用 302ed 实际图像 url http://a1.twimg.com/profile_images/1272489576/Photo_38_normal.jpg
但无论我尝试什么,我都无法读取重定向的绝对 URL。还有其他想法吗?
编辑:我不希望这变成一个时间槽,所以我只使用了
http://api.twitter.com/1/users/show.json?user_id=
API 调用。我以为这需要对受保护用户进行经过身份验证的调用,但它不需要,所以可以使用。
【问题讨论】:
-
它被调用了两次,但使用相同的 src:jsfiddle.net/ionutzp/6Ekub
标签: javascript jquery image redirect twitter