Bootstrap-3-Typeahead 获得正确的 json 键

Bootstrap-3-Typeahead getting right json key

我将此插件用于 ajax 自动完成功能 https://github.com/bassjobsen/Bootstrap-3-Typeahead bootstrap-3 类型。下面的代码有效,但我不知道它为什么有效。具体来说,过程和响应参数是如何工作的。

$(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" 但结果未定义

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

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

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

其次,"source" 属性 的文档说:要查询的数据源。可以是一个字符串数组,一个 JSON 对象数组,名称为 属性 或一个函数。

因此,您提供给 "process" 方法的最有可能应该是字符串数组或 JSON 对象数组,其中每个 JSON 对象都有一个 "name" 属性。 如果您的回答是正确的并且 returns 像您所说的对象数组, 那么这意味着你的对象每个都有一个'name' 属性,所以显示属性。如果你想显示别的东西,你需要从响应中创建一个新的字符串数组:

所以我会试试这个:

 .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);
});