未捕获的类型错误:对象不可迭代(无法读取属性 Symbol(Symbol.iterator))在 XMLHttpRequest。<anonymous>
2022-03-13
725
const container = document.querySelector("#container");
request.open("GET","https://datausa.io/api/data?drilldowns=Nation&measures=Population") ;
request.send();
// to get the response
request.addEventListener("load",function(){
// console.log( this.responseText);
const [data]= JSON.parse(this.responseText);
console.log(data);
// const htmlData ="<div></div>";
// container.insertAdjacentHTML("afterbegin",htmlData)
})
我在 JSON.parse(this.responseText) 中收到错误,上面提到的错误是针对这一行的,请帮我解决
2个回答
您不需要用 [] 或 {} 包围 data 。在这种情况下,只需 data 就足够了。
const data = JSON.parse(this.responseText);
Marcin Soczówka
2022-06-13
调用返回以下内容:
{"data":[{"ID Nation":"01000US","Nation":"United States","ID Year":2019,"Year":"2019","Population":328239523,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2018,"Year":"2018","Population":327167439,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2017,"Year":"2017","Population":325719178,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2016,"Year":"2016","Population":323127515,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2015,"Year":"2015","Population":321418821,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2014,"Year":"2014","Population":318857056,"Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID Year":2013,"Year":"2013","Population":316128839,"Slug Nation":"united-states"}],"source":[{"measures":["Population"],"annotations":{"source_name":"Census Bureau","source_description":"The American Community Survey (ACS) is conducted by the US Census and sent to a portion of the population every year.","dataset_name":"ACS 1-year Estimate","dataset_link":"http://www.census.gov/programs-surveys/acs/","table_id":"B01003","topic":"Diversity","subtopic":"Demographics"},"name":"acs_yg_total_population_1","substitutions":[]}]}
如您所见,这是一个对象而不是数组,因此要从对象中获取数据键,您需要使用大括号而不是普通括号。
像这样:
const {data} = JSON.parse(this.responseText);
mgm793
2022-03-13