jQuery UI Autocomplete using a static json file as source

前端 未结 2 694
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 12:46

I\'m using jquery-ui-autocomplete (actually, a catcomplete attached to a search box). It works vey well as long as I use a static-defined a

相关标签:
2条回答
  • 2020-12-29 13:10

    Try flipping it around, so on page-load you grab it once, then instantiate the autocomplete.

    $(function() {
        $.ajax({
            url: "/path/to/cache.json",
            dataType: "json",
            data: {term: request.term},
            success: function(data) {
                var cat_data = $.map(data, function(item) {
                    return {
                        label: item.label,
                        category: item.category,
                        desc: item.desc
                    };
                });
                $("#searchfield").catcomplete({
                    delay: 0,
                    source: cat_data,
                    minlength:0
                });
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-29 13:14

    Your datasource is throwing an parse error since the json format is not propper, in json the keys also have to be enclosed within ".

    {
      "list" : [{
                    "label" : "lbl1",
                    "category" : "cat1",
                    "desc" : "desc1"
                }, {
                    "label" : "lbl2",
                    "category" : "cat1",
                    "desc" : "desc2"
                }, {
                    "label" : "lbl3",
                    "category" : "cat1"
                }]
    }
    

    Demo: Plunker

    If you want the request term based searches, then you will have to make some more changes

      var xhr;
      $( "input" ).catcomplete({
        delay: 0,
        source: function( request, response ) {
          var regex = new RegExp(request.term, 'i');
          if(xhr){
            xhr.abort();
          }
          xhr = $.ajax({
              url: "data.json",
              dataType: "json",
              cache: false,
              success: function(data) {
                response($.map(data.list, function(item) {
                  if(regex.test(item.label)){
                    return {
                        label: item.label,
                        category: item.category,
                        desc: item.desc
                    };
                  }
                }));
              }
          });
        },
        minlength:0
      });
    

    Demo: Plunker

    0 讨论(0)
提交回复
热议问题