[英]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.