使用jquery检查json文件中的图像的src是否为空

时间:2017-04-17 06:50:53

标签: jquery json

我正在尝试使用javascript和jQuery中的Google Knowledge Graph Search API Link从Google获取图片。 Google返回的json文件类似于下面这个:

{
  "@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 Knowledge Graph中获取10张图片。但是,Google Knowledge Graph中并非所有图片都可用,即其中的某些网址可能是空的。我想检查图像的url是否为空,图像将被添加到document.body;否则,将添加图像不可用的错误消息。问题是下面这句话对我不起作用。

if ($(img).attr('src') !== '')   

我只获得了第一张图片,然后循环停止移动以检查其余部分。有人可以为我指点方向吗?我没有运气就google了很多。非常感谢。

2 个答案:

答案 0 :(得分:1)

if(element['result']['image']['contentUrl'] != null) {
       //add image
       src = element['result']['image']['contentUrl'];
}  else {
         //show "image is not available" text
}

答案 1 :(得分:1)

检查Fiddle

JS:

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) { 
            if(typeof element.result.image !== 'undefined')
            {
               img = $('<img>', { src: element.result.image.contentUrl });    
                if ($(img).attr('src') !== '') {
                    img.appendTo(document.body);
                    $('body').append('</br>'); 
                    }          

                }
                else {
                    $('body').append('<p>image is not available</p></br>'); 
                }
            });
        });