我的应用程序中有一个自动完成功能,它向服务器发出 ajax 请求。 但是,一旦我从服务器获取数据,我想使用查找功能而不是使用服务 url(以尽量减少对服务器的调用)。
这是我的 js 的样子
$('#country').autocomplete({
serviceUrl : './countryCache?',
paramName : 'countryName',
transformResult : function(response) {
return {
// must convert json to javascript object before process
suggestions : $.map($.parseJSON(response), function(item) {
return {
data : item.name
};
})
};
},
showNoSuggestionNotice:true,
onSelect: function (value, data) {
$('#countryId').val(value.data);
}
});
这是我对 countryCache 的 ajax 调用的示例 - “India, Iceland, Indonesia”。 如果用户输入了 I,服务器返回如上的结果。 现在,当用户在我之后输入 n 时,我不想再次调用服务器。 谁能帮我实现它。
最佳答案
jQuery UI Autocomplete documentation 中有一个简单的解决方案.您会在此处找到标题为带缓存的远程 的部分,其中显示了如何实现您正在寻找的内容。
我将该站点的代码改编为这个问题,并添加了一些注释以进行澄清:
var cache = {};
$( "#country" ).autocomplete({
source: function( request, response ) {
// If the term is in the cache, use the already existing values (no server call)
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
// Add countryName with the same value as the term (particular to this question)
// If the service reads the parameter "term" instead, this line can be deleted.
request.countryName = request.term;
// Call the server only if the value was not in the cache
$.getJSON( "./countryCache", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
},
select: function (event, data) {
$('#countryId').val(data.item.value);
}
});
因为我不知道 JSON 的确切格式,所以我只使用了一个基本的格式,用于返回文本“In”:["India","Indonesia","Spain"]
(没有 ID,只是一个普通数组)。
如果您使用的是 Ajax AutoComplete plugin for jQuery (上面的代码看起来像,虽然问题被标记为 jquery-ui-autocomplete ),那么您不必担心缓存,因为插件会自动为您完成。
来自插件的文档:
noCache
: Boolean value indicating whether to cache suggestion results. Defaultfalse
.
因为你没有给nocache
指定任何值,那么它会取默认值false
,直接执行缓存。
关于javascript - 在 jquery 自动完成中使用查找和/或服务 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561289/