【问题标题】:Get response from API with jQuery使用 jQuery 从 API 获取响应
【发布时间】:2017-07-04 07:40:37
【问题描述】:

我想在输入字段中输入一些内容,然后从 API 中获取值是否存在的响应。

如果邮政编码 (12345) 存在,API 将以真/假值响应。 http://192.168.100.100:8887/public?zipcode=12345

到目前为止,这是我的代码:

$(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。

【问题讨论】:

  • 你给了一个本地 ip ;)
  • 操作!我会写出 JSON!
  • 你正在循环一个布尔值?
  • 是的。只有真或假

标签: jquery json api


【解决方案1】:

我添加了一个简单的 if else 语句,结果很好。虽然不知道该不该用这个方法:

//Checks keys
if (result) {
    $('.positiveMessage').show()
} else {
    $('.negativeMessage').show()
}

【讨论】:

  • 是的,这是一个比循环布尔值更好的解决方案
  • 好的!谢谢你这么快回复彼得。对此,我真的非常感激。顺便说一句,当我搜索一个不存在的值时,我的 .negativeMessage 显示,但是当我搜索一个确实退出我的 .positiveMessage 显示的值时,但我的其他消息不会消失。有什么想法吗?
【解决方案2】:

那里有一些 ES6(成功函数中的左箭头)可能无法按预期工作。当您已经拥有 jQuery 时,您还可以使用 getElementById。

没有 API 提要很难回答,但这至少应该可以帮助您获得响应。使用 console.log 打印 API 返回的内容,然后您应该能够遍历到您需要的数据。

$(function() {
    $('.positiveMessage, .negativeMessage').hide()
    $('#submitBtn').on('click', function() {
        var zipCode = $('#searchZipCode').val();
        $.getJSON({
            type: 'GET',
            url: 'http://192.168.100.100:8887/public?zipcode=' + zipCode,
            success: function(result){
                if (result) {
                    $('.positiveMessage').show()
                    $('.negativeMessage').hide()
                } else {
                    $('.positiveMessage').hide()
                    $('.negativeMessage').show()
                }
            }
        })
    })
})

【讨论】:

    【解决方案3】:

    你可以使用这个技巧:

    $('.positiveMessage').show();
    var time_hide = 1000; // in ms
    setTimeout(function(){
        $('.positiveMessage').hide();
    }, time_hide);
    

    【讨论】:

    • 聪明的想法,但我想知道一个持续到用户再次搜索的组件是否更好。 思考的脸
    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 2018-05-21
    • 1970-01-01
    • 2014-09-16
    • 2013-01-20
    • 2012-04-21
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多