最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jQuery autocomplete with json file? - Stack Overflow

programmeradmin4浏览0评论

I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autoplete 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').autoplete({
        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'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autoplete 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').autoplete({
        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);
            });
            )
            });
        }    
    });
});
Share Improve this question asked Mar 14, 2017 at 19:57 HannanHannan 551 gold badge3 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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

$( function() {
	$.getJSON("http://neil.puter/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" ).autoplete({
			source: autoComplete
		});
	});
});
<link rel="stylesheet" href="//code.jquery./ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery./jquery-1.12.4.js"></script>
<script src="https://code.jquery./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 .autoplete("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.autoplete({
      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
          })
      }
    })
    .autoplete("instance")._renderItem = function(ul, item) {
      return $("<li>", {
        html: item.value
      }).appendTo(ul)

  };

jsfiddle http://jsfiddle/wr1wg5df/11/

发布评论

评论列表(0)

  1. 暂无评论