jquery-ui 自动完成操作不正确

Incorrect operation of the jquery-ui autocomplete

当您在输入中输入单个字符时重新加载页面后,立即没有任何反应。当您输入以下字符时开始补码。

获取数据

`function getData(data, callback) {
            $.ajax({
                url: "myUrl" + encodeURIComponent(data),
                method: "GET",
                dataType: "JSON",
                success: callback
            })
        }`

回调函数

 `function autocompleteInput () {
       var dataInput = $("#myInput").val();
       function success(data) {
         var dataArr = [];
         for (var i = 0; i < data.data.length; i++) {
           dataArr.push(data.data[i].name);
               }
                    $("#myInput").autocomplete({
                        source: brokersNameArr,
                        delay: 500,
                        minLength: 1
                    })
                  getData(dataInput, success);
       }`

在html中使用

$("#myInput").keyup($.throttle(200, autocompleteInput));

建议如下:

var dataArr = [];
$("#myInput").autocomplete({
  source: function(req, resp){
    $.getJSON("myurl?" + req.term, function(results){
      $.each(results.data, function(k, r){
        dataArr.push(r.name);
      });
      resp(results);
    });
  },
  delay: 500,
  minLength: 1
});

您可能还想查看:http://jqueryui.com/autocomplete/#multiple-remote

使用 source 的函数将使您能够管理数据的发送和接收方式。

Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:

  • A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".

  • A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

希望对您有所帮助。