我设法创建了一个有效的推特类型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”时,正在处理的“机场”对象如下所示:
["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个结果有重复,以及 应该在此时过滤掉的重复记录。
我是否需要以某种方式在通话之间等待,或者检查是否有重复?我不太确定如何处理这个问题,并希望得到一些意见或建议。
答案 0 :(得分:5)
通过移动解决问题
airports = [];
成功函数内部。