【问题标题】:Bootstrap-3-Typeahead getting right json keyBootstrap-3-Typeahead 获取正确的 json 密钥
【发布时间】:2016-06-22 23:34:51
【问题描述】:

我正在使用这个插件来实现 ajax 自动完成功能 https://github.com/bassjobsen/Bootstrap-3-Typeahead bootstrap-3 类型。下面的代码有效,但我不知道它为什么有效。具体来说 process 和 response 参数是如何工作的。

$(document).ready(function() {
    $('#typeahead-input').typeahead({
        autoSelect: true,
        minLength: 1,
        delay: 400,
        source: function (query, process) {
            $.ajax({
                url: '/api/location',
                data: {sstr: query},
                dataType: 'json'
            })
                .done(function(response) {

                    // console.log(response)
                    return process(response);
                });
        }
    });
});

我的 json 看起来像这样

[
    {
        "id": "123", 
        "name": "Frederiksted", 
        "state": "VI", 
        "zip_code": "840"
    }
]

如果我想根据 zip_code 字段自动完成填充怎么办? 我试过做“response.zipcode”,但结果是未定义的

【问题讨论】:

    标签: javascript jquery ajax twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    首先,response.zipcode 将是未定义的,因为 response 是一个数组而不是一个对象。您通过 response[0].zip_code 访问邮政编码(还要注意,您的属性名称不是 'zipcode' 它是 'zip_code' )。

    其次,“源”属性的文档说:要查询的数据源。可以是字符串数组、带有名称属性的 JSON 对象数组或函数。

    因此,您给予“process”方法的内容很可能应该是字符串数组或 JSON 对象数组,其中每个 JSON 对象都有一个“name”属性。 如果你的回答是正确的,并且像你说的那样返回一个对象数组, 那么这意味着您的对象每个都有一个“名称”属性,因此会显示该属性。如果要显示其他内容,则需要从响应中创建一个新的 String 数组:

    所以我会试试这个:

     .done(function(response) {
         // get the response and create a new array of Strings
         var names = $.map (response, function(item) {
              return item.name + '-' + item.zip_code;
         });
         // console.log(response)
         return process(names);
        });
    

    或其他方式:

    .done(function(response) {
     // get the response and change the 'name' of each object
     $.each (response, function() {
           this.name = this.name + '-' + this.zip_code;
     });
     // console.log(response)
     return process(response);
    });
    

    【讨论】:

    • 谢谢你。您提供的代码运行良好。但是,如果我只想要 zip_code 我应该做什么呢? $.each (response, function() { this.name = this.zip_code; });?当我搜索 zip_code 时,它​​对我不起作用
    • 我不认为插件会自动以数字完成,但会用名字谢谢你的帮助
    • 尝试将数字转换为字符串 this.name=this.zip_code.toString();
    • 顺便说一句,邮政编码通常存储为字符串而不是数字,这使得使用字符串长度验证器等更容易验证。如果在数值计算或比较中未使用某些内容,则可能不是字符串一个数字。
    • 谢谢你这么聪明。 ^_^
    【解决方案2】:

    我认为您对 json 格式有疑问:

    [ “id”:“123”, "name": "弗雷德里克斯特德", “状态”:“六”, “邮编”:“840” ]

    【讨论】:

    • 检查这个网址,看看它是如何工作的。
    • 感谢您尝试帮助我。该示例无法解决任何问题。它没有显示如何为多选使用不同的键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多