为了账号安全,请及时绑定邮箱和手机立即绑定

检索 json 特定属性?

检索 json 特定属性?

跃然一笑 2021-12-23 14:48:53
我正在使用新闻 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.responsevar 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
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

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)

}


查看完整回答
反对 回复 2021-12-23
?
UYOU

TA贡献1878条经验 获得超4个赞

进行以下更改,它将起作用:


for(var i;i<=parsedData.length;i++)

{

    //create a title for the news

    var allArticles = parsedData.articles[i].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)

}


查看完整回答
反对 回复 2021-12-23
  • 2 回答
  • 0 关注
  • 161 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号