使用jQuery从API获取响应
我想在输入字段中键入一些内容,然后从API获得一个响应(如果该值存在或不存在) 如果zipcode(12345)存在,API将以真/假值响应 这是我到目前为止的代码:使用jQuery从API获取响应,jquery,json,api,Jquery,Json,Api,我想在输入字段中键入一些内容,然后从API获得一个响应(如果该值存在或不存在) 如果zipcode(12345)存在,API将以真/假值响应 这是我到目前为止的代码: $(function() { $('.positiveMessage, .negativeMessage').hide() $('#submitBtn').on('click', function() { var $zipcode = document.getElementById('search
$(function() {
$('.positiveMessage, .negativeMessage').hide()
$('#submitBtn').on('click', function() {
var $zipcode = document.getElementById('searchZipCode').value
$.getJSON({
type: 'GET',
url: 'http://192.168.100.100:8887/public?zipcode=' + $zipCode,
success: result => {
//Goes through the array
$.each(result, function(i, info) {
$('body').append(info + '')
})
}
})
})
})
如您所见,我希望通过在链接中添加一个变量来操作API 我添加了一个简单的if-else语句,结果很好。虽然我不知道我是否应该使用这种方法:
//Checks keys
if (result) {
$('.positiveMessage').show()
} else {
$('.negativeMessage').show()
}
您有一些ES6(success函数中的左箭头)可能无法按预期工作。当您已经拥有jQuery时,您还使用了getElementById 没有API提要很难回答,但这至少可以帮助您获得响应。使用console.log打印API返回的内容,然后您应该能够遍历到所需的数据
$(函数(){
$('.positiveMessage,.negativeMessage').hide()
$(#submitBtn')。在('click',function()上{
var zipCode=$('#searchZipCode').val();
$.getJSON({
键入:“GET”,
网址:'http://192.168.100.100:8887/public?zipcode=“+zipCode,
成功:功能(结果){
如果(结果){
$('.positiveMessage').show()
$('.negativeMessage').hide()
}否则{
$('.positiveMessage').hide()
$('.negativeMessage').show()
}
}
})
})
})
您可以使用以下技巧:
$('.positiveMessage').show();
var time_hide = 1000; // in ms
setTimeout(function(){
$('.positiveMessage').hide();
}, time_hide);
您正在提供本地ip;)行动!我将写出JSON!你在循环一个布尔值?是的。只有正确或错误是的,这是一个比循环通过布尔值更好的解决方案好吧!谢谢你这么快回复,彼得。我真的很感激。顺便说一句,当我搜索一个不存在的值时,会显示我的
。negativeMessage
,但当我搜索一个确实退出的值时。positiveMessage
也会显示,但我的其他消息不会消失。有什么想法吗?这个想法很聪明,但我想知道,如果一个组件能持续到用户再次搜索,我会更好。思考面