我正在尝试调用REST API,并且抛出如下错误
[Show/hide message details.] TypeError: data.forEach is not a function
我是REST API的新手。
我的API结构如下
{
"Agents":
{
"@ZipCode": "33176",
"Agent": [
{
"AgencyID": "21",
"Name": "Anakarina Callejas",
"Phone": "305-515-5613",
"CityName": "KENDALL",
"Address": "10471 N Kendall Dr. #101. Miami, FL 33176",
"Reviews-Rating": "5",
"Reviews-Count": "74",
"image": "/images/agents/21.png"
},
{
"AgencyID": "116",
"Name": "Tamara Mourino",
"Phone": "305-256-0616",
"CityName": "PINECREST",
"Address": "12745 South Dixie Highway. #101. Pinecrest, FL 33156",
"Reviews-Rating": "5",
"Reviews-Count": "70",
"image": "/images/agents/116.png"
}]
}
}
我的API调用就像这样
var request = new XMLHttpRequest();
request.open('GET', 'URL to the API', true);
request.onload = function () {
var data = JSON.parse(this.response);
data.forEach(agent => {
console.log(agent.Name);
});
}
request.send();
答案 0 :(得分:2)
从您的API结构看,您的data
是object
而不是array
。
首先从Agent array
对象获取data
,然后对其进行迭代以获取每个name
的{{1}}。
Agent
示例数据片段:
var responseData =JSON.parse(responseData);
var data= responseData.Agents.Agent;
data.forEach(agent => {
console.log(agent.Name);
});