API缩略图图像返回TypeError:无法读取undefined的“url”

时间:2016-01-21 06:28:01

标签: javascript jquery json api

我正在使用NYT API来获取文章的缩略图/图像。但是我的某些图片出现Cannot read property "url" of undefined错误。这是终端的截图。

Screenshot

由于它说“url”未定义,我决定检查(在我的函数中)图像源是否返回undefined

var prefix = "http:\/\/static01.nyt.com\/";
var src = prefix + data.multimedia[2].url;
if(!src || src == undefined) { src = "img/img-nyt.png"; }
else { imgSource = src; }
console.log(imgSource);

但是我不确定为什么它仍会返回undefined因为如果是,那么图像源应该更改为img-nyt.png

以下是示例JSON请求:

"results": [
    {
        "multimedia":[
            {
                "url":"http:\/\/static01.nyt.com\/images\/2016\/01\/20\/us\/20michigan-web\/20michigan-web-thumbStandard.jpg",
                "height":75,
                "width":75,
            },
            {
                "url":"http:\/\/static01.nyt.com\/images\/2016\/01\/20\/us\/20michigan-web\/20michigan-web-thumbLarge.jpg",
                "height":150,
                "width":150,
            },
            {
                "url":"http:\/\/static01.nyt.com\/images\/2016\/01\/20\/us\/20michigan-web\/20michigan-web-articleInline.jpg",
                "height":127,
                "width":190,
            }
        ]
    }
]

这是我的函数整个函数,它从JSON获取值:

// MAKES THE REQUEST AND DISPLAYS THE NEWS BASED ON RESULTS
    function searchArticles(term) {
        viewing.innerHTML = term;
        term = term.replace(/ /g, "+");
        searchURL = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + term + "&api-key=" + searchAPI;
        var prefix = "http:\/\/static01.nyt.com\/";
        mainDivToAppendTo.innerHTML = null;
        $.getJSON(searchURL, function(api) {
            var i = 0;
            api.response.docs.forEach(function(data) {
                link = data.web_url;
                var src = prefix + data.multimedia[2].url;
                if(!src || src == undefined) { src = "img/img-nyt.png"; }
                else imgSource = src;
                console.log(imgSource);
                cardTitle = (data.headline.main.length > 43) ? data.headline.main.substring(0, 43) + " .." : data.headline.main;
                postedBy = "In " + data["section_name"];
                i++;
                createCardElements();
            });
            numberOfPosts.innerHTML = i + " results";
        });
    }

我似乎无法弄清楚这有什么问题。也许我只是错过了一些非常明显的东西。希望我能得到一些帮助..

以下是您可以查看的整个:示例网址:

http://api.nytimes.com/svc/search/v2/articlesearch.json?q=donald-trump&api-key=sample-key

1 个答案:

答案 0 :(得分:0)

而不是检查是否data.multimedia[0].url == undefined 我需要检查data.multimedia[0] == undefined

我仍然得到错误,因为它试图从未定义的对象获取url并且做了魔术。