JavaScript — TypeAhead не показывает результаты запроса

я очень отчаялся!

У меня есть эта проблема с Bootstrap Typeahead.

HTML-разметка:

<div class="form-group">
<label for="">Recipients</label>
<input id="recipients" name="recipients"autocomplete="off"class="form-control"data-role="tagsinput">
</div>

JavaScript:

$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
hint: true,
highlight: true,
minLength: 4,
limit: 10,
source: function (query) {
$.ajax({
url: "/app/route",
type: 'POST',
dataType: 'JSON',
data: {'query' : query},
success: function(data) {
console.log(data);
return(data);
}
});
},
afterSelect: function() {
this.$element[0].value = '';
}
}
});

После вызова Ajax я получаю этот массив в утешении:

["Justin Demetria +393281893574", "Dylan Alea +393700488191", "Zahir Tatyana +393007841301", "Ryan Veda +393542236060", "Hunter Wanda +393393156943"]

Проблема: я ничего не вижу 🙁 ничего не появляется. Typeahead не работает.

В консоли я получаю эту ошибку

bootstrap-tagsinput.js Uncaught TypeError: Cannot read property 'success' of undefined.

Как я могу это исправить?

Я использую Bootstrap 3, последний источник Typeahead js.

-2

Решение

Джеймс, теперь мой вызов ajax:

$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
source: function(queryForHints) {
if (queryForHints.length < 4)
return '';
var parameters = {'queryForHints': queryForHints};
jQuery.ajax({
url: "/app/route",
data: parameters,
type: "POST",
dataType: "json",
success: function(data) {
var sourceData = [];
for (var i = 0; i < data.length; i++) {
sourceData.push(data[i].text);
}
return (sourceData);
},
error: function(data) {
console.log("error for xxxxx/xxxxx");
},
async: true
});
}
}
});

Но ошибка сохраняется:

bootstrap-tagsinput.js:331 Uncaught TypeError: Cannot read property 'success' of undefined

ошибка в строке 331 bootstrap-tagsinput.js, и я нахожу:

if ($.isFunction(data.success)) {
// support for Angular callbacks
data.success(processItems);

Можем ли мы решить проблему?

по моему скромному мнению, проблема в том, что теги input не могут понять УСПЕХ вызова ajax

1

Другие решения

Для typehhead используйте Bloodhound, чтобы получить ваши данные, а не ajax.

Ваш код должен выглядеть примерно так:

var customers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/customers?query=%QUERY',
wildcard: '%QUERY'
}
});

$('#customer').typeahead({
minLength: 3,
highlight: true
}, {
name: 'customers',
display: 'name',
source: customers
}).on("typeahead:select", function(e, customer) {
vm.customerId = customer.id;
});

Для получения дополнительной информации о Bloodhound:
Bloodhound @ GitHub

И вот несколько примеров для typeahead: Примеры TypeAhead

0