【问题标题】:Caching autocomplete JSON responses缓存自动完成 JSON 响应
【发布时间】:2015-06-01 04:11:43
【问题描述】:

是否有任何特殊技巧或要求让浏览器缓存 JSON API 响应以实现自动完成等功能?

  • 我们有一个表格,它采用建筑物名称
  • 大约有 1500 个建筑物名称,因此我们不想不必要地下载所有这些名称
  • 我们在输入至少两个字符后发送 API 查询,例如到 api.website.com/autocomplete?q=as

我需要在客户端做什么,这样如果用户键入内容然后删除,他们就不会重新查询。例如他们输入a-s-p-<delete>-t 如何防止重复的?q=as 查询发生?如果我包含一个 Cache-Control 标头,我原以为这是自动的,但它似乎不起作用。

【问题讨论】:

    标签: jquery json api caching autocomplete


    【解决方案1】:

    这是我与 jQuery 自动完成一起使用的(阅读 cmets)。它在客户端缓存结果,因此您无需处理服务器/浏览器缓存。这个特定示例用于简单的供应商名称查找:

    // 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 
    });
    

    基本上,您在按术语索引的对象中跟踪搜索结果。如果您搜索相同的术语,您将获得缓存的结果。还有一些额外的代码用于取消和重用当前正在运行的 AJAX 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2012-10-08
      • 2011-01-24
      相关资源
      最近更新 更多