我有一个大小为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会说:

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

最佳答案

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



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

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

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

程序:

  • 首先使用 $.getJSON 下载整个数据
  • 然后将数据分成10,000个大块(这对我来说是一个神奇的数字,适用于所有浏览器。找到您的名字)
  • 为每个块创建一组猎犬,并将所有内容存储在数组中。
  • 然后使用该数组
  • 初始化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,只是为了说明多数据集通常如何工作。 (搜索肖恩或本杰明)

    希望这可以帮助。

    10-05 20:52
    查看更多