首页 > 解决方案 > JQuery自动完成返回空白结果

问题描述

我正在使用 jquery 自动完成和来自远程源的一些 geojson 数据。问题是结果列表是空白的。我猜这可能是数据格式问题。当用户搜索某些内容时,我只需要在自动完成时显示“标签”字段。

$(function() {
  function log(message) {
    $("<div>").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }
  $('#birds').autocomplete({
    source: function(request, response) {
      $.getJSON("https://geosearch.planninglabs.nyc/v1/autocomplete?text=" + request.term, function(data) {
        response($.each(data.features, function(key, value) {
          console.log(value.properties.label);
          return {
            label: value.properties.label,
            value: key
          };
        }));
      });
    },
    minLength: 2,
    delay: 100
  });
});
.ui-autocomplete-loading {
  background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<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="birds">Birds: </label>
  <input id="birds">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

标签: javascriptjqueryjquery-ui

解决方案


我想你可能有点$.each()困惑$.map()。考虑以下代码:

$(function() {
  function log(message) {
    $("<div>").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }

  $('#birds').autocomplete({
    source: function(request, response) {
      $.getJSON("https://geosearch.planninglabs.nyc/v1/autocomplete?text=" + request.term, function(data) {
        var results = [];
        $.each(data.features, function(key, value) {
          console.log(value.properties.label);
          results.push({
            label: value.properties.label,
            value: key
          });
        });
        response(results);
      });
    },
    minLength: 2,
    delay: 100
  });
});
.ui-autocomplete-loading {
  background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<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="birds">Birds: </label>
  <input id="birds">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

如您所见,return不需要$.each(). 它为数据源中的每个项目执行函数。您想构建一个结果数组,response()一旦获得所有结果,就可以将其传回。

希望这可以帮助。


推荐阅读