3

我设法创建了一个有效的 twitter typeahead ajax 调用。

我遇到了输入太快时项目重复的问题。

示例场景:

当您尝试获取“Casablanca”时,您会开始输入,并期望当您到达“casa”时,它会被相对较好地过滤。不幸的是,这些项目是重复的,所以我没有 2 或 3 个选项,而是 9 到 20 D:

这是正在调用的 JS:

$(".airportSearch").typeahead({
    source: function(query, process) {
        airports = [];
        map = {};

        $.ajax({
            url: url_,
            dataType: "json",
            data: {
                n: 12, q: query
            },
            success: function(data) {
                    $.each(data, function (i, record) {
                    map[record.airport] = record;
                    airports.push(record.city + ", " + record.airport + " (" + record.iata + "), " + record.country);
                });

                process(airports);
            }
        });
    },
    minLength: 1,
    items: 11,
    sorter: function (items) {
        return items.sort();
    },
    updater: function (item) {
        selectedState = map[item].iata;
        return item;
    }
});

如果我慢慢打字,效果会很好,但众所周知,我不能指望人们有耐心!

当我输入“casa”时,我正在调用的 servlet 的响应只有 3 条记录长:

[
{"type":"airport","city":"Casablanca","airport":"Anfa","iata":"CAS","country":"Morocco","locationId":"airport_CAS"},
{"type":"airport","city":"Casablanca","airport":"Mohammed V","iata":"CMN","country":"Morocco","locationId":"airport_CMN"},
{"type":"airport","city":"Casa Grande Municipal, AZ","airport":"Casa Grande Municipal","iata":"CGZ","country":"United States","locationId":"airport_CGZ"}
]

不幸的是,那里似乎有一些愚蠢的事情正在发生,我一直无法找到。当我输入“casa”时,正在处理的“airports”对象如下所示:

["Casablanca, Anfa (CAS), Morocco", 
"Casablanca, Mohammed V (CMN), Morocco", 
"Casa Grande Municipal, AZ, Casa Grande Municipal (CGZ), United States",
"Cascade Locks, OR, Cascade Locks (CZK), United States",
"Cascavel, Cascavel (CAC), Brazil",
"Casigua, Casigua (CUV), Venezuela",
"Casino, Casino (CSI), Australia",
"Casper, WY, Casper (CPR), United States",
"Cassilandia, Cassilandia (CSS), Brazil",
"Castaway, Castaway (CST), Fiji",
"Castlegar, Castlegar (YCG), Canada",
"Castres Mazamet, Castres Mazamet (DCM), France", 
"Castro Gamboa, Castro Gamboa (WCA), Chile", 
"Casablanca, Anfa (CAS), Morocco",
"Casablanca, Mohammed V (CMN), Morocco", 
"Casa Grande Municipal, AZ, Casa Grande Municipal (CGZ), United States",
"Casablanca, Anfa (CAS), Morocco", 
"Casablanca, Mohammed V (CMN), Morocco",
"Casa Grande Municipal, AZ, Casa Grande Municipal (CGZ), United States"]

如您所见,我当时期望的 3 个结果存在重复项,以及此时本应过滤掉的记录的重复项。

我是否需要在通话之间以某种方式等待,或者检查重复项?我不太确定如何解决这个问题,希望能提供一些意见或建议。

4

1 回答 1

5

搬家解决了问题

airports = [];

在成功函数内部。

于 2013-08-08T14:56:57.823 回答