Are there are any particular tricks or requirements for getting browsers to cache JSON API responses for something like autocomplete?
What do I need to do on client side so that if a user types something and then deletes, that they don't requery. eg they type asp-<delete>-t
how can I prevent duplicate ?q=as
queries from occurring? I had expected this to be automatic if I include a Cache-Control header but it doesn't seem to be working.
This is what I use with jQuery autocomplete (read comments for purpose). It caches the results client-side so you don't need to deal with server/browser caching. This particular example was for a simple vendor name lookup:
// 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
});
Basically you keep track of the search results in an object indexed by term. If you search for the same term, you get the cached results. There's some extra code for cancelling and reusing the currently running AJAX request as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.