Javascript 调用RESTAPI并显示搜索的结果
我正在从这个Javascript 调用RESTAPI并显示搜索的结果,javascript,jquery,rest,Javascript,Jquery,Rest,我正在从这个HTML表单调用restapi <form action="#"> <h1>Enter your zip code</h1> <div class="form-group"> <label for="zip">Zip Code</label> <input type="text" id="zip"> </div> <di
HTML
表单调用restapi
<form action="#">
<h1>Enter your zip code</h1>
<div class="form-group">
<label for="zip">Zip Code</label>
<input type="text" id="zip">
</div>
<div class="button-holder">
<button class="btn btn-primary" onclick="callREST()">Next</button>
</div>
</form>
这就是我调用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 < 400) {
data.forEach(agent => {
// Log each agent's title
console.log(agent.Name);
});
} else {
console.log('error');
}
}
// Send request
request.send();
}
函数callREST(){
//创建一个请求变量并为其分配一个新的XMLHttpRequest对象。
var request=new XMLHttpRequest();
//使用URL端点上的GET请求打开新连接
open('GET','URL to the API',true);
request.onload=函数(){
//从这里开始访问JSON数据
var responseData=JSON.parse(this.response);
var数据=responseData.Agents.Agents;
如果(request.status>=200&&request.status<400){
data.forEach(代理=>{
//记录每个代理的标题
console.log(agent.Name);
});
}否则{
console.log('error');
}
}
//发送请求
request.send();
}
我获得所有数据,但我需要的只是与
输入字段中输入的邮政编码匹配的数据您可以从代理
对象获得@ZipCode值,并与输入值进行比较
var responseData =JSON.parse(jsonResponse);
var zipCode= responseData.Agents['@ZipCode'];
如果输入值
与示例数据“zipCode
值匹配,则显示警报
的工作代码段
var jsonResponse='{“Agents”:“{@ZipCode”:“33176”,“Agent”:[{“AgencyID”:“21”,“Name”:“Anakarina Callejas”,“Phone”:“305-515-5613”,“CityName”:“KENDALL”,“Address”:“10471 N KENDALL Dr.#101.迈阿密,佛罗里达33176”,“评论评级”:“5”,“评论计数”:“74”,“image”:“images/images/Agents/21.png”,{“AgencyID”:“116”,“Name”:“Tamara Mourino”,“Phone”:“305-256-0616”,“城市名称”:“PINECREST”,“地址”:“12745南迪克西公路.#101.PINECREST,FL 33156”,“评论评级”:“5”,“评论计数”:“70”,“图片”:“/images/agents/116.png”}}”;
函数callREST(){
event.preventDefault();//用于演示以防止表单提交。
var inputZip=document.getElementById(“zip”).value;
var responseData=JSON.parse(jsonResponse);
var zipCode=responseData.Agents['@zipCode'];
//log(inputZip,zipCode);
if(zipCode==inputZip){
警报(“ZipCode匹配”);
}否则{
警报(“ZipCode不匹配”);
}
}
输入您的邮政编码
邮政编码
下一个
代理
是对象还是数组?为邮政编码编写if条件。@ZohaibIjaz它应该是一个object@ShakeerHussain但是我首先要如何获得邮政编码呢?我对REST API非常陌生,所以如果您能帮助我,我将不胜感激。@ZohaibIjaz您会注意到代理
是对象而代理
有数组
var responseData =JSON.parse(jsonResponse);
var zipCode= responseData.Agents['@ZipCode'];