使用JQuery UI自动完成从JSON搜索数据不起作用

Searching data from JSON using JQuery UI autocomplete not working

本文关键字:JSON 搜索 数据 不起作用 JQuery UI 使用      更新时间:2023-09-26

如何使用JQuery UI自动完成提取的json数据?它对我不起作用。

我用这个例子http://jqueryui.com/autocomplete/,但我从json中获取的不是硬编码数据。

我的json数据来自一个url localhost/myproject/output/names

html

<input type="text" class="form-control" name="search" placeholder="Search" id="search">

js

<script>
  $(function() {
    $( "#search" ).autocomplete({
      source: "localhost/myproject/output/names"
    });
  });
  </script>

json数据

[{"fullname":"John Smith"},{"fullname":"Juan dela Cruz"}]

编辑

正如@artm所评论的那样,我已经设法解决了json数据的问题。现在是[{John Smith},{Juan dela Cruz}]

但另一个问题是,当我键入字母o时,尽管只有John Smith包含o,但建议同时使用两者。我该怎么解决这个问题?

jQuery UI自动完成需要一个字符串数组,例如
["John Smith", "Juan dela Cruz"]

或者具有labelvalue属性的对象数组,例如:

[ { label: "name", value: "John Smith" }, { label: "name", value: "Juan dela Cruz" }... ]

如果您的数据源不是以这种格式直接发送数据,您可以将函数传递给source选项,在该选项中,您可以从数据源检索数据并相应地进行修改。

函数接收两个参数:

  • 具有单个term属性的请求对象,其值为用户输入
  • 一个回调函数,您应该以正确的格式将数据传递给它

试试

$(function() {
  $( "#search" ).autocomplete({
   source: function(request, response){
     $.ajax("localhost/myproject/output/names",{ // retrieve the data
          //ajax settings
         success: function(data){
            var matches = $.map(data,function(item){ // create an array of strings
               // find the matching items manually in insert to the array
               if(item.fullname.indexOf(request.term)>=0)
                 return item.fullname;
            });
            response(matches); // pass the results to response callback
         }
     });
   }
  });
});

附带说明:代码没有经过测试,只是为了给出一个大致的概述。