我有一个静态json文件,其中包含json格式的数据。现在,我已经使用jquery插件实现了自动完成功能。我的问题是自动完成显示所有结果,包括不必要的结果。按照我的javascript代码,
$('input#searchBox').autocomplete({
source: function( request, response ) {
$.ajax({
url: "${pageContext.request.contextPath}/products_cache.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data.products, function(item) {
return {
value: item.product,
label: item.product,
key: item.id
};
}));
}
});
},
minlength:2,
select: function(event, ui) {
$("#searchBox").val(ui.item.key);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
我的json文件包含以下格式的数据,
{
"products": [
{
"id":"1",
"product": "product1"
},
{
"id":"2",
"product": "product2"
},
{
"id":"3",
"product": "product3"
},
{
"id":"4",
"product": "product4"
},
{
"id":"5",
"product": "product5"
}
]
}
理想情况下,当我输入类似ab的输入时,自动完成功能不应提供任何建议。如何过滤掉不需要的值?
答案 0 :(得分:1)
我不知道基于ajax的jQuery。但我试过你的代码。如果您收到错误,请忽略我的回答。
var ProductArray = [];
$('input#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/products_cache.json",
dataType: "json",
data: { term: request.term },
success: function(data) {
$.each(data, function(key, value) {
ProductArray[key] = value.product;
});
// \\b show each match letter in each word of list
// ^ show each match letter in whole word of list
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(ProductArray, function(item, index) {
return matcher.test(item);
});
response(a);
}
});
},
minlength: 2,
select: function(event, ui) {
$("#searchBox").val(ui.item.key);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
这就是我使用自动完成的方式。我的jQuery代码(示例)......
点击here例如
==== jQuery
$(document).ready(function() {
GetLocalityList();
});
function GetLocalityList() {
var LocalityArray = ["win the day", "win the heart of", "win the heart of someone"];
$("#tags").autocomplete({
minLength: 1,
source: function(req, responseFn) {
// \\b show each match letter in each word of list
// ^ show each match letter in whole word of list
var matcher = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(req.term), "i");
var a = $.grep(LocalityArray, function(item, index) {
return matcher.test(item);
});
responseFn(a);
}
});
}
==== HTML
<body>
<div>
<label for="tags">
Search :
</label>
<input type="text" id="tags">
</div>
</body>