jQuery UI 多选自动完成未在 html 页面中显示数据

jQuery UI Autocomplete with multiple selection is not showing data in html page

我正在尝试使用具有多项选择功能的自动完成文本框。但是,我在使用 jQueryUi 的自动完成组件时遇到了一些麻烦。带有自动完成建议的列表未正确显示。 从服务器我得到了这样的值:

[{"id":"1","text":"Test1 [1001]"},{"id":"2","text":"Test2 [1002]"}]

但它没有显示在 UI。在 UI 是这样的:

这是我的 HTML 代码:

<label class="control-label">Group <span class="symbol required" aria-required="true"></span></label>
<input type="text" class="form-control" id="HSModels" tablename="ProductInfo" required />
<input type="hidden" class="form-control" id="HSModelsID" required />

我的脚本:

 $("#HSModels")
            .bind("keydown", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("ui-autocomplete").menu.active) {
                    event.preventDefault();
                }
            })
            .autocomplete({
                minLength: 2,
                source: function (request, response) {
                    $.getJSON("/api/Common/AutoCompleteListDataByTableName", { tableName: "ProductInfo", query: request.term },
                        response
                        );
                },
                search: function () {
                    // custom minLength
                    var term = extractLast(this.value);
                    if (term.length < 2) {
                        return false;
                    }
                },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    var HSModelsIDVal = $("#HSModelsID").val();
                    HSModelsIDVal += ", " + ui.item.id;
                    $("#HSModelsID").val(HSModelsIDVal)

                    var terms = split(this.value);
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push(ui.item.value);
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            //});
        });
        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }

在服务器端:

[HttpGet]
public HttpResponseMessage AutoCompleteListDataByTableName(string tableName, string query = "")
        {
            GenericRepository<DropdownListData> repository = new GenericRepository<DropdownListData>(_csmDb);

            try
            {
                var parameters = new List<SqlParameter> { new SqlParameter("@TableName", tableName), new SqlParameter("@QueryText", query) };
                List<DropdownListData> dataList = repository.ExecuteStoreProcedureToList("[GetAutoCompleteListDataByTableName]", parameters);
                return Request.CreateResponse(HttpStatusCode.OK, dataList, RequestFormat.JsonFormaterString());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = ex.Message }, RequestFormat.JsonFormaterString());
            }          

        }

有什么想法吗?而且我遇到了另一个问题,即在选择一个之后它不再加载数据。

在firebug:

第一次:GET http://localhost:40315/api/Common/AutoCompleteListDataByTableName?tableName=ProductInfo&query=te

第二次: 获取 http://localhost:40315/api/Common/AutoCompleteListDataByTableName?tableName=ProductInfo&query=%2C+te

我正在尝试做某事 like this

提前致谢。

要完成您想要的,您必须遵循您提到的示例和“Custom Data & Display”的示例。这是我的建议:

工作示例:https://jsfiddle.net/Twisty/gr5LL10o/

jQuery

$(function() {
  $("#HSModels")
    .bind("keydown", function(event) {
      if (event.keyCode === $.ui.keyCode.TAB &&
        $(this).data("ui-autocomplete").menu.active) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 2,
      source: function(request, response) {
        /*
          $.getJSON("/api/Common/AutoCompleteListDataByTableName", {
              tableName: "ProductInfo",
              query: request.term
            },
            response
          );
          */
          // Example search for demonstration, using jsfiddle AJAX system
        $.ajax({
          url: "/echo/json/",
          type: "POST",
          data: {
            json: JSON.stringify([{
              "id": "1",
              "text": "Test1 [1001]"
            }, {
              "id": "2",
              "text": "Test2 [1002]"
            }, {
              "id": "3",
              "text": "Apple [1003]"
            }, {
              "id": "4",
              "text": "Banana [1004]"
            }])
          },
          success: function(data) {
            var results = [];
            var term = extractLast(request.term).toLowerCase();
            $.each(data, function(k, v) {
              if (v.text.toLowerCase().indexOf(term) === 0) {
                console.log("Found " + v.text);
                results.push(v);
              }
            });
            console.log("Responding with ", results);
            response(results);
          }
        });
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
      /*
        var HSModelsIDVal = $("#HSModelsID").val();
        HSModelsIDVal += ", " + ui.item.id;
        $("#HSModelsID").val(HSModelsIDVal)
      */
        var labels = split(this.value);
        var ids = split($("#HSModelsID").val());
        // remove the current input
        labels.pop();
        ids.pop();
        // add the selected item
        labels.push(ui.item.text);
        ids.push(ui.item.id);
        // add placeholder to get the comma-and-space at the end
        labels.push("");
        ids.push("");
        this.value = labels.join(", ");
        $("#HSModelsID").val(ids.join(","));
        return false;
      }
    }).autocomplete("instance")._renderItem = function(ul, item) {
      return $("<li>")
        .append("<div>" + item.text + "</div>")
        .appendTo(ul);
    };

  function split(val) {
    return val.split(/,\s*/);
  }

  function extractLast(term) {
    return split(term).pop();
  }
});

您的原始代码表面上没有任何问题。您的数据比标准数据数组更复杂。你还用它做了更多,而不仅仅是列一个清单。

出于示例的目的,我绕过了 AJAX 对 API 的调用。我假设从查找返回的数据如下所示:

[{
    "id": "1",
    "text": "Test1 [1001]"
}, {
    "id": "2",
    "text": "Test2 [1002]"
}, {
    "id": "3",
    "text": "Apple [1003]"
}, {
    "id": "4",
    "text": "Banana [1004]"
}]

这是我的示例数据,您的数据已被过滤。所以在你的脚本中,成功函数会简单得多,更像是:

success: function(data){
  response(data),
},

在选择阶段,我们将对结果做更多​​的工作。我们想要创建一个标签和 ID 数组。因此,当用户选择特定标签时,我们会更新该数组,并更新我们稍后可以使用的相应 ID 数组。

我就是这样做的,我创建了一个包含当前选定的所有标签的数组和一个包含当前选定的所有 ID 的数组。我们删除该数组中的最后一个条目,对于标签,这将是搜索词的一部分,对于 ID,这将是空的。我们将最近的选择推到数组的末尾并将它们写入各自的字段。

我们要做的最后一点整理工作是租用结果列表项。因为我们不需要 ID,所以我们基本上省略它,只用文本标签制作一个 li。

哒哒!如果您有任何问题,请发表评论并告诉我。