是空的,我想使用JavaScript和jQuery的谷歌的知识图谱搜索API Link从谷歌获得的图像。从谷歌返回的JSON文件类似于下面这样:检查,如果图像在JSON文件中的SRC使用jQuery
{
"@context": {
"@vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"detailedDescription": "goog:detailedDescription",
"EntitySearchResult": "goog:EntitySearchResult",
"kg": "http://g.co/kg"
},
"@type": "ItemList",
"itemListElement": [
{
"@type": "EntitySearchResult",
"result": {
"@id": "kg:/m/0dl567",
"name": "Taylor Swift",
"@type": [
"Thing",
"Person"
],
"description": "Singer-songwriter",
"image": {
"contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
"url": "https://en.wikipedia.org/wiki/Taylor_Swift",
"license": "http://creativecommons.org/licenses/by-sa/2.0"
},
"detailedDescription": {
"articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
"url": "http://en.wikipedia.org/wiki/Taylor_Swift",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
},
"url": "http://taylorswift.com/"
},
"resultScore": 896.576599
}
]
}
用于此目的的JavaScript代码的主要部分如下:
<script>
var service_url = 'https://kgsearch.googleapis.com/v1/entities:search';
var params = {
'query': 'Taylor Swift',
'limit': 10,
'indent': true,
'key' : 'AIzaSyBpCW-EUz2EqI8YIjmQYYXwTzZu8kXGPEw',
};
var img;
$.getJSON(service_url + '?callback=?', params, function(response) {
$.each(response.itemListElement, function(i, element) {
img = $('<img>', {
src: element['result']['image']['contentUrl']
});
if ($(img).attr('src') !== '') {
img.appendTo(document.body);
}
else {
$('body').html('<p>image is not available</p>');
}
});
});
</script>
你可以从javascript代码看,我我试图从Google知识图谱中获取10张图片。但是,并非所有图片都可以在Google知识图谱中找到,也就是说,其中某些图片可能为空。我想检查图像的URL是否为空,图像将被添加到document.body;否则,将会添加图像等错误消息。问题是下面这句话对我不起作用。
if ($(img).attr('src') !== '')
我只得到了第一个图像,然后循环停止移动,检查休息。任何人都可以为我指出一个方向吗?我没有任何运气搜索了很多东西。提前致谢。
不是检查的IMG SRC你为什么不检查的contentURL价值? –