【问题标题】:typeahead.js, localStorage and large json Filetypeahead.js、localStorage 和大型 json 文件
【发布时间】:2015-03-21 11:57:09
【问题描述】:

我有一个大小为 1Mb 的 JSON 文件。 我尝试用一​​个简单的例子来实现 typeahead.js:

    <div class="container">
    <p class="example-description">Prefetches data, stores it in localStorage, and searches it on the client: </p>
    <input id="my-input" class="typeahead" type="text" placeholder="input a country name">
  </div>
  
   <script type="text/javascript">
    // Waiting for the DOM ready...
    $(function(){

      // applied typeahead to the text input box
      $('#my-input').typeahead({
        name: 'products',

        // data source
        prefetch: '../php/products.json',

        // max item numbers list in the dropdown
        limit: 10
      });

    });
  </script>

但是当我启动它时,Chrome 会说:

未捕获的 QuotaExceededError:无法在“存储”上执行“setItem”: 设置 '__products__itemHash' 的值超出了配额。

我能做什么?我正在使用 typeahead.min.js

【问题讨论】:

  • 可能是浏览器中设置的首选项、每台计算机上的可用磁盘空间或其他一些环境差异。相关问题link

标签: javascript json google-chrome typeahead.js typeahead


【解决方案1】:

您看到该错误是因为预先输入预取使用 localStorage 来存储数据。

首先,在客户端存储 1MB 的数据在用户体验方面并不是很好。

鉴于此,您仍然可以解决多数据集的问题。这只是一种解决方法,可能不是最优雅的解决方案,但效果很好。

我测试的样本数据>1MB,看起来像这样

您可以查看示例here(打开需要一段时间)

程序:

  1. 首先使用$.getJSON下载整个数据
  2. 然后将数据分成 10,000 个块(这对我来说是一个神奇的数字,在浏览器中都适用。找到你的)
  3. 为每个块创建了一组猎犬,并将所有内容存储在一个数组中。
  4. 然后使用该数组初始化 typeahead

代码:

$.getJSON('data.json').done(function(data) { // download the entire data
  var dataSources = [];
  var data = data['friends'];
  var i, j, data, chunkSize = 10000; // break the data into chunks of 10,000
  for (i = 0, j = data.length; i < j; i += chunkSize) {
    tempArray = data.slice(i, i + chunkSize);
    var d = $.map(tempArray, function(item) {
      return {
        item: item
      };
    });
    dataSources.push(getDataSources(d)); // push each bloodhound to dataSources array
  }
  initTypeahead(dataSources); // initialize typeahead 
});

function getDataSources(data) {
  var dataset = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('item'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: data,
    limit: 1 // limited each dataset to 1 because with 76,000 items I have 8 chunks and each chunk gives me 1. So overall suggestion length was 8
  });
  dataset.initialize();
  var src = {
    displayKey: 'item',
    source: dataset.ttAdapter(),
  }
  return src;
}

function initTypeahead(data) {
  $('.typeahead').typeahead({
    highlight: true
  }, data); // here is where you use the array of bloodhounds
}

我创建了一个演示 here,其中包含 20 个项目,chunkSize 为 2,只是为了展示多数据集通常如何工作。 (搜索 Sean 或 Benjamin)

希望这会有所帮助。

【讨论】:

  • 哇,这是一个令人印象深刻的答案,非常感谢。也谢谢你的提示。也许我会尽量不使用 LocalStorage ..
  • Localstorage 通常很好,但对于这种规模的文件,它可能是有风险的。我很高兴答案有帮助
猜你喜欢
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多