简体   繁体   中英

Display data in autocomplete jQuery UI

I created an autocomplete function, when I console.log it displays me all my files that is in remote JSON file, but When I try to display it when I start Type on input it doesn't show nothing, no errors but it doesn't work at all. Also I want to make this multi select autocomplete. But right now I want it only display suggestions when I start type on input.

$(function () {
  $("#city").autocomplete({
    source: function (request, response) {
      $.ajax({
        url: $('#city').attr('data-source'),
        success: function (data) {
          for (var i = 0; i < data.length; i++) {
            data[i].loc_name
          }
        }
      })
    }
  })
})

JSON

[{"population":1729119,"token":"167|7|179|1296|55544|0","loc_name":"Warszawa"},{"population":758463,"token":"167|6|135|976|7644|0","loc_name":"Krak\u00f3w"},{"population":718960,"token":"167|5|113|789|58247|25218","loc_name":"\u0141\u00f3d\u017a Teofil\u00f3w"},{"population":718960,"token":"167|5|113|789|58247|25340","loc_name":"\u0141\u00f3d\u017a G\u00f3rna"},{"population":718960,"token":"167|5|113|789|58247|25282","loc_name":"\u0141\u00f3d\u017a \u0141askowice"}]

The issue is because your AJAX logic isn't quite right. Once the AJAX completes you need to provide the received data to the response callback, like this:

$("#city").autocomplete({
  source: function (request, response) {
    $.ajax({
      url: $('#city').data('source'),
      success: function(data) {
        var output = data.map(function(o) {
          return {
            label: o.loc_name,
            value: o.token
          }
        });
        response(output);
      }
    })
  }
})

This is assuming that the format that data is returned in matches the format that autocomplete expects. If not you'll have to modify the array - preferably on the server.

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