检索 json 特定属性?

我正在使用新闻 API 从不同的新闻来源检索与我们不同的新闻。API 调用成功,但HTML无法在循环中检索信息并使用它填充页面。例如,在新闻 API 中,如果我尝试检索新闻的描述并HTML在循环中使用它填充页面,它会给我一个未定义的错误。


此代码一次适用于其中一篇文章,但在 for 循环中检索所有文章则无效。 var allArticles =parsedData.articles[0].description;console.log(allArticles);


`var request = new XMLHttpRequest;


request.open('GET','https://newsapi.org/v2/top-headlines? 

country=us&apiKey=5060977c4cef473e8e06cb2ad53ea674')


request.onload = function(){

var response = request.response

var parsedData = JSON.parse(response)

console.log(parsedData)


for(var item in parsedData)

{

    //create a title for the news

    var allArticles = parsedData.articles[item].description;

    console.log(allArticles);


    //create the element on html

    var titleElement = document.createElement('p');



    titleElement.innerHTML = allArticles;


    //place it inside the body

    document.body.appendChild(titleElement)

}

}


request.onerror = function(){

console.log("There appears to be problem accessing the API")

}

request.send();`

控制台显示错误代码:


Uncaught TypeError: Cannot read property 'description' of undefined

    at XMLHttpRequest.request.onload


跃然一笑
浏览 162回答 2
2回答

慕尼黑的夜晚无繁华

for(var item in parsedData.articles){    //create a title for the news    var allArticles =item.description;    console.log(allArticles);    //create the element on html    var titleElement = document.createElement('p');    titleElement.innerHTML = allArticles;    //place it inside the body    document.body.appendChild(titleElement)}

UYOU

进行以下更改,它将起作用:for(var i;i<=parsedData.length;i++){&nbsp; &nbsp; //create a title for the news&nbsp; &nbsp; var allArticles = parsedData.articles[i].description;&nbsp; &nbsp; console.log(allArticles);&nbsp; &nbsp; //create the element on html&nbsp; &nbsp; var titleElement = document.createElement('p');&nbsp; &nbsp; titleElement.innerHTML = allArticles;&nbsp; &nbsp; //place it inside the body&nbsp; &nbsp; document.body.appendChild(titleElement)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript