我正在使用新闻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