【问题标题】:Read the absolute redirected SRC attribute URL for an image读取图像的绝对重定向 SRC 属性 URL
【发布时间】: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 调用。我以为这需要对受保护用户进行经过身份验证的调用,但它不需要,所以可以使用。

【问题讨论】:

标签: javascript jquery image redirect twitter


【解决方案1】:

而不是使用

http://api.twitter.com/1/users/profile_image/<user_id>

API调用,我用过

http://api.twitter.com/1/users/show.json?user_id=

而是从那里提取头像 URL。它不是轻量级的,因为它也会返回大量其他用户数据,但即使是受保护的用户头像也无需身份验证即可返回,因此它是一个合适的替代品。

【讨论】:

    【解决方案2】:

    这里的代码只加载一次: http://jsfiddle.net/ionutzp/6Ekub/1/

    avatar_loaded = function(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";
    
    $(window).load(function(){
            var img = new Image();
            $(img).load(function(){avatar_loaded(this)}).attr('src',avatar_url).appendTo('body');
           //jQuery('body').append("<img onload='' src='" + avatar_url + "' width='100' height='100'>");
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 2013-09-22
    • 2013-07-26
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多