[英]jQuery autocomplete UI - doesn't work
I am trying to make an autocomplete widget that will display item's codes returned from a database. 我正在尝试创建一个自动完成小部件,它将显示从数据库返回的项目代码。
I have successfully made it so my database will return the appropriate JSON response. 我已成功完成,因此我的数据库将返回相应的JSON响应。
The problem now is I don't know why the drop-down list doesn't show up. 现在的问题是我不知道为什么下拉列表没有出现。
Here's the code down below: 这是下面的代码:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. 应加载具有AJAX加载数据的自动完成功能。
source
property can be a function which accepts a callback parameter. source
属性可以是接受回调参数的函数。 You should feed this callback with data loaded from server. 您应该使用从服务器加载的数据来提供此回调。
Also you don't need to bind keyup
event manually. 您也不需要手动绑定
keyup
事件。 Your code will become: 您的代码将变为:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.