如何使用json自动完成与json文件?

时间:2017-03-14 19:57:48

标签: javascript jquery json ajax autocomplete

我正在学习Ajax和jQuery并尝试使用json文件作为数据源。我正在使用jQuery UI自动完成小部件来帮助用户选择一个选项。我知道我非常偏离赛道。

我的json文件:

[
    {"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"}
]

我的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);
            });
            )
            });
        }    
    });
});

2 个答案:

答案 0 :(得分:0)

我修复了一些语法错误,然后编写了这个例子来真正让你开始。

$( 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>

答案 1 :(得分:0)

您可以将html推送到request的数组,将数组传递到response.autocomplete("instance")._renderItem使用<li>创建html元素设置为第二个参数item.value属性,该html设置在request内并传递给response;将<li>附加到来自ul的第一个参数returnul ._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/