typeahead.js,localStorage和大型json文件

So4*_*4ne 6 javascript json google-chrome typeahead typeahead.js

我有一个大小为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>
Run Code Online (Sandbox Code Playgroud)

但是当我推出它时,chrome说:

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

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

Dhi*_*raj 8

您看到该错误,因为typeahead prefetch使用localStorage来存储数据.

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

鉴于此,您仍然可以使用多个数据集解决问题.这只是一种解决方法,可能不是最优雅的解决方案,但它完美无缺.

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

在此输入图像描述

你可以在这里查看样本(打开需要一段时间)

程序:

  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
}
Run Code Online (Sandbox Code Playgroud)

我在这里创建了一个包含20个项目和chunkSize为2 的演示,以显示多个数据集通常如何工作.(搜索肖恩或本杰明)

希望这可以帮助.