简体   繁体   中英

How to use jQuery autocomplete with json file?

I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autocomplete widget to help user select one option. I know I'm terribly off the track.

My json file:

[
    {"iata":"AAC", "name":"El Arish"},
    {"iata":"AAE", "name":"Annabah"},
    {"iata":"AAF", "name":"Apalachicola"},
    {"iata":"AAG", "name":"Arapoti"},
    {"iata":"AAH", "name":"Aachen"},
    {"iata":"AAI", "name":"Arraias"},
    {"iata":"AAJ", "name":"Awaradam"},
    {"iata":"AAK", "name":"Buariki"},
    {"iata":"AAL", "name":"Aalborg"},
    {"iata":"AAM", "name":"Malamala"},
    {"iata":"AAN", "name":"Al Ain"}
]

My JavaScript:

$(document).ready(function () {
    $('#search').autocomplete({
        source: function (request, response) {
            var searchField = $('#search').val();
            var myExp = new RegExp(searchField, "i");
            $.getJSON("beta.json", function (data) {
                var output = '<ul class="searchresults">';
                $.each(data, function (key, val) {
                    if ((val.iata.search(myExp) !== -1) ||
                            (val.name.search(myExp) !== -1)) {
                        output += '<li>';
                        output += '<h2>' + val.iata + '</h2>';
                        output += '<p>' + val.name + '</p>';
                        output += '</li>';
                    }
                });
                output += '</ul>';
                $('#update').html(output);
            });
            )
            });
        }    
    });
});

I fixed some syntax errors and then wrote up this example to really get you jump started.

 $( function() { $.getJSON("http://neil.computer/stack/beta.json", function(data) { autoComplete = []; for (var i = 0, len = data.length; i < len; i++) { autoComplete.push(data[i].name + ", " + data[i].iata); } $( "#tags" ).autocomplete({ source: autoComplete }); }); }); 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags"> </div> 

You can push html to an array at request , pass array to response , at .autocomplete("instance")._renderItem create an <li> element with html set to second argument item , .value property, which should be html set within request and passed to response ; append <li> to first argument ul , return ul from ._renderItem

  var elem = $("#search");
  $.ajaxSetup({
    context: elem
  });
  elem.autocomplete({
      minLength: 1,
      source: function(request, response) {
        $.getJSON("beta.json")
          .then(function success(data) {
            var searchField = elem.val();
            var myExp = new RegExp(searchField, "i");
            var res = [];
            $.each(data, function(key, val) {
              if ((val.iata.search(myExp) !== -1) ||
                (val.name.search(myExp) !== -1)) {
                res.push("<h2>" + val.iata + "</h2>" + "<p>" + val.name + "</p>")
              }
            });
            response(res);

          }, function error(jqxhr, textStatus, errorThrown) {
            console.log(textStatus, errorThrown) // log `$.ajax` errors
          })
      }
    })
    .autocomplete("instance")._renderItem = function(ul, item) {
      return $("<li>", {
        html: item.value
      }).appendTo(ul)

  };

jsfiddle http://jsfiddle.net/wr1wg5df/11/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM