[英]Caching autocomplete JSON responses
是否有任何特定的技巧或要求让浏览器缓存自动完成等内容的JSON API响应?
我需要在客户端做什么,以便在用户输入内容然后删除时,他们不会重新查询。 例如,他们键入asp-<delete>-t
如何防止重复?q=as
查询发生? 如果我包含一个Cache-Control标头,我原本以为这是自动的,但它似乎不起作用。
这是我使用jQuery自动完成功能(为了目的阅读注释)。 它缓存客户端的结果,因此您不需要处理服务器/浏览器缓存。 这个特殊的例子是一个简单的供应商名称查找:
// An obbject/map for search term/results tracking
var vendorCache = {};
// Keep track of the current AJAX request
var vendorXhr;
$('#VendorName').autocomplete({
source: function (request, response) {
// Check if we already searched and map the existing results
// into the proper autocomplete format
if (request.term in vendorCache) {
response($.map(vendorCache[request.term], function (item) {
return { label: item.name, value: item.name, id: item.id };
}));
return;
}
// search term wasn't cached, let's get new results
vendorXhr = $.ajax({
url: 'path/to/vendor/controller',
type: 'GET',
dataType: 'json',
data: { query: request.term },
success: function (data, status, xhr) {
// cache the results
vendorCache[request.term] = data;
// if this is the same request, return the results
if (xhr === vendorXhr) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id };
}));
}
}
});
},
focus: function (event, ui) {
$('#VendorId').val((ui.item ? ui.item.id : ''));
},
select: function (event, ui) {
$('#VendorId').val((ui.item ? ui.item.id : ''));
},
minLength: 3 // require at least three characters from the user
});
基本上,您可以跟踪由term索引的对象中的搜索结果。 如果搜索相同的术语,则会获得缓存的结果。 还有一些额外的代码用于取消和重用当前运行的AJAX请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.