我正在使用新闻 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
跃然一笑
慕尼黑的夜晚无繁华
UYOU
随时随地看视频慕课网APP
相关分类