使用 url 从 jQuery UI 自动完成中获取列表选项

Get list options from jQuery UI autocomplete with url

我的元素是一个 jQuery 自动完成元素,其选项来自 URL:

$element.autocomplete({
    source: '/mysearchurl',
    open: function () {
        //...
    },
    response: function (event, ui) {
        //...
    },
    select: function (event, ui) {
        //...
    }
});

它按预期工作:用户输入一些字符,并在下拉列表中显示匹配值。

我现在想要的是,在我的 Javascript 中,从列表中取出选项,理想情况下与从 URL 中获得的选项相同 JSON。我可以尝试通过这样的方式从元素中收集它们:

$($element.data('ui-autocomplete').menu.element[0].list.childNodes).each()

但也许有更好的方法?

我建议使用 source 函数并在内部调用 Ajax:

$("#autocomplete").autocomplete({
  source: function(request, response) {
    var el = this.element;
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");

    $.ajax({
      url: "https://api.myjson.com/bins/qnhcd",
      type: "GET",
      contentType: "application/json",
      dataType: "json",
      success: function(data, textStatus, jqXHR) {
        var selection = data.filter(function(item) {
          if (matcher.test(item.value)) return item.value;
        });
        el.data("source", selection);
        response(selection);
      }
    });

  }
});

$( "#autocomplete" ).on( "autocompleteresponse", function( event, ui ) {
 refreshList();
});

refreshList = function() {
  var source = $("#autocomplete").data("source");
  console.log("refreshList", source);

  $("#list").empty();
  if (source) {
    for (var i in source) {
      $("#list").append("<li>" + source[i].value + "</li>")
    }
  } else {
    $("#list").append("<li>No options</li>")
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<br>
<button onclick="refreshList()">
refresh list
</button>
<br>
<ol id="list">
</ol>

这是一个 jsfiddle:http://jsfiddle.net/beaver71/svLsw13f/