gpt4 book ai didi

javascript - 9gag 解析 json

转载 作者:行者123 更新时间:2023-11-30 18:13:12 24 4
gpt4 key购买 nike

我想从中随机挑选一张图片:

http://9gag.com/top/all/index/page/1?view=json

为了正确显示它,我需要知道这张图片的大小。

我使用 YQL 将这个 json 的结果放在一个变量中(称为 source)。

我将 https 替换为 http 并删除每个反斜杠。

var it = $.parseJSON(source);
var total = it.count-1;
var random = Math.floor((Math.random()*total)+0);
var gagurl = it.items[random];
var gagurldecode = gagurl.replace('\\','');
gagurldecode = gagurldecode.replace('https','http'); //here is the url of the image

但我无法检索此图像的大小。

   var img = new Image();
img.src = gagurldecode;

警报(img.height);什么都不返回。

如果我替换

img.src = gagurldecode;

img.src = 'http://d24w6bsrhbeh9d.cloudfront.net/photo/1777377_460s.jpg';

有效。

我做错了什么?PS:对不起我的英语!

最佳答案

这一行是不必要的,因为解析 JSON 时斜杠被转义了:

var gagurldecode = gagurl.replace('\\','');

对于您的实际问题,heightwidth 直到图像下载并检查后才会填充。如果浏览器没有看到图像(在 onload 事件处理程序中),这是异步完成的,但如果像硬编码示例中那样从缓存中检索,则可以同步完成:

img.onload = function() {
alert(img.height);
}

这每次都有效。

关于javascript - 9gag 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com