处理从ajax调用返回

时间:2013-08-08 11:16:46

标签: ajax twitter-bootstrap bootstrap-typeahead

我正在使用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变量,并确认它是我创建的对象的预期列表。我想用对象列表中的returnvalue字符串填充自动完成选项。

有人能告诉我怎么做,或者指点我告诉我怎么样?

1 个答案:

答案 0 :(得分: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_vals进行预先输入,但我会按照您的原因按照您的方式进行操作。

希望它有所帮助。