jQueryUI自动完成响应索引问题

jQuery UI auto-complete response index problem

我正在使用 jQuery ui-complete 库,它通过获取请求调用端点来填充建议的作者列表:

$("#author-name").autocomplete({
                source: "/authors/get.json",
                minLength: 5,
                select: function(event, ui) {
                    event.preventDefault();
                    $("#author-name").val(ui.item.label);
                    $("#author-id").val(ui.item.value);
                }

});

问题在于回复的格式,它包含在索引数组中,如下所示:

{
    "reply": [
        {
            "value": 9,
            "label": "Joe Bloggs"
        },
    ]
}

是否可以从回复对象中判断要处理的响应,例如:

select: function(event, ui.reply) {

我已阅读库中的 api 文档,但找不到解决方案。

如果你使用 ECMAScript 6,你可以使用对象解构:

select: function(event, { reply }) {

reply 现在将成为您使用 ui.reply 访问的内容。

你也可以这样使用

select: function(event, ui) {
                event.preventDefault();
                var reply = ui.reply;
//And Because it is an array you should use index on it.
                $("#author-name").val(reply[0].label);
                $("#author-id").val(reply[0].value);
            }

source 需要一个数组,因此您将不得不调整分配给它的内容。
在下面的示例中,我只是创建了一个新函数来获取数据访问 reply 数组,这就是我传递给自动完成的内容 source

$(document).ready(function() {

  function getResponse() {
    var response = {
      "reply": [{
          "value": 9,
          "label": "Joe Bloggs"
        },
        {
          "value": 10,
          "label": "foo"
        },
      ]
    }; // in your case: read data from /authors/get.json

    return response.reply;
  }

  $("#tags").autocomplete({
    source: getResponse(),
    select: function(event, ui) {
      event.preventDefault();
      console.log(ui.item.value);
      console.log(ui.item.label);
    }
  });
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>