如何使用大型JSON文件作为数据源进行自动完成搜索?

时间:2018-01-18 22:00:47

标签: javascript jquery json jquery-ui-autocomplete

我正在尝试使用包含数百万行的JSON大文件来构建自动完成搜索栏。

为了获得更好的性能,不希望对PHP脚本发出Ajax请求,这样就会对数据库产生%%的请求。

我开始使用JQuery来实现它,但我无法使JSON功能起作用。

在处理大型json文件时,有哪些方法可以改进下面的代码以获得更好的性能?

非常感谢!

这是HTML:

<!DOCTYPE html>
<html>

  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Search</title>

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/redmond/jquery-ui.css">

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <script type="text/javascript">

    </script>
  </head>

  <body>
    <input />
  </body>

</html>

这是javascript,无法正常运行:

$(function() {
  $.widget("custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
      var that = this,
        currentCategory = "";
      $.each(items, function(index, item) {
        if (item.name != currentCategory) {
          ul.append("<li class='ui-autocomplete-name'>" + item.name + "</li>");
          currentCategory = item.name;
        }
        that._renderItemData(ul, item);
      });
    }
  });

  $("input").catcomplete({
    delay: 0,
    source: function(request, response) {
      $.ajax({
        url: "data.json",
        dataType: "json",
        data: {
          term: request.term
        },
        success: function(data) {
          var cat_data = $.map(data, function(item) {
            return {
              name: item.name
            };
          });
          $("#searchfield").catcomplete({
            delay: 0,
            source: cat_data,
            minlength: 0
          });
        }
      });
    },
    minlength: 0
  });
});

这是JSON数据:

[{
    "unit":12345,
    "name":"Car Batteries",
    "type":"HardGood",
    "price":0.50,
    "category":[
        {"id":"1","name":"Automobile"},
        {"id":"2","name":"Batteries"}]}
{
    "unit":2345,
    "name":"Soap",
    "type":"Hygiene",
    "price":1.00,
    "category":[
        {"id":"3","name":"Hygiene"},
        {"id":"4","name":"Bathroom"}]}
{
    "unit":56573,
    "name":"Camera",
    "type":"Photography",
    "price":700.50,
    "category":[
        {"id":"6","name":"Photography"},
        {"id":"7","name":"Gadgets"}]}
{
    "unit":94893,
    "name":"iPhone Cable",
    "type":"Cables",
    "price":0.50,
    "category":[
        {"id":"19","name":"Cables"},
        {"id":"20","name":"Mobile"}]}]

0 个答案:

没有答案