0

我正在使用 twitter-bootstrap 的 typeahead 对输入字段进行自动完成。

到目前为止我所拥有的:

$(".airportSearch").typeahead({
    source: function(typeahead, query) {
        $.ajax({
            url: url_,
            dataType: "json",
            data: {
                n: 12,
                q: typeahead
            },
            success: function(data) {
                var return_list = [], i = data.length;
                while(i--) {
                    return_list[i] = {
                        type: data[i].type,
                        id: data[i].iata,
                        value: data[i].city,
                        returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
                            data[i].city + ' (' + data[i].iata + ')'
                    };
                }

            }
        });
    }
});

输出示例:

[{"type":"airport","city":"Quebec","airport":"Quebec","iata":"YQB","country":"Canada","locationId":"airport_YQB"},
{"type":"airport","city":"Queenstown","airport":"Queenstown","iata":"ZQN","country":"New Zealand","locationId":"airport_ZQN"},
{"type":"city","city":"Setif","airport":"All Airports","iata":"QSF","country":"Algeria","locationId":"DZ_city_QSF"},
{"type":"airport","city":"Setif","airport":"Setif","iata":"QSF","country":"Algeria","locationId":"airport_QSF"},
{"type":"airport","city":"QachaS Nek","airport":"QachaS Nek","iata":"UNE","country":"Lesotho","locationId":"airport_UNE"},
{"type":"airport","city":"Qaisumah","airport":"Qaisumah","iata":"AQI","country":"Saudi Arabia","locationId":"airport_AQI"}]

我已经记录了我创建的 return_list 变量,并确认它是我创建的预期对象列表。我想用对象列表中的返回值字符串填充自动完成选项。

谁能告诉我怎么做,或者指向一个告诉我怎么做的地方?

4

1 回答 1

1

尝试这个:

$(".airportSearch").typeahead({
    source: function(typeahead, process) {
        return $.ajax({ // return ajax result
            url: url_,
            dataType: "json",
            data: {
                n: 12,
                q: typeahead
            },
            success: function(data) {
                var return_list = [], i = data.length, data_vals = []; // add data_vals array for typeahead
                while(i--) {
                    return_list[i] = {
                        type: data[i].type,
                        id: data[i].iata,
                        value: data[i].city,
                        returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
                            data[i].city + ' (' + data[i].iata + ')'
                    };

                    data_vals.push(return_list[i].returnvalue); // populate the needed values
                }
                return process(data_vals); // and return to typeahead
            }
        });
    }
});

通常我只会填充data_valsfor typeahead 但你这样做是出于你的原因,我猜。

希望能帮助到你。

于 2013-08-08T12:21:37.593 回答