呼叫restapi并显示搜索结果

我从这个HTML表单调用REST API

 

Enter your zip code

我的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的方式

 function callREST() { // Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest(); // Open a new connection, using the GET request on the URL endpoint request.open('GET', 'URL to the API', true); request.onload = function () { // Begin accessing JSON data here var responseData = JSON.parse(this.response); var data = responseData.Agents.Agent; if (request.status >= 200 && request.status  { // Log each agent's title console.log(agent.Name); }); } else { console.log('error'); } } // Send request request.send(); } 

我得到了所有数据,但我需要的只是与input fieldinput fieldZIP Code相匹配的数据

您可以从Agents对象获取@ZipCode值并与input value进行比较。

 var responseData =JSON.parse(jsonResponse); var zipCode= responseData.Agents['@ZipCode']; 

以下是工作代码段,如果input value与示例数据的zipCode值匹配,则显示alert

  var jsonResponse='{"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"}]}}'; function callREST() { event.preventDefault();//for demo to prevent form submit. var inputZip=document.getElementById("zip").value; var responseData =JSON.parse(jsonResponse); var zipCode= responseData.Agents['@ZipCode']; //console.log(inputZip,zipCode); if(zipCode==inputZip){ alert("ZipCode matched."); }else{ alert("ZipCode not matched."); } } 
 

Enter your zip code