使用JQuery UI自动完成function从JSON搜索数据无法正常工作
如何使用获取的json数据使用JQuery UI自动完成? 它不适用于我的。
我使用这个例子http://jqueryui.com/autocomplete/ ,而不是我从json获取的硬编码数据。
我的json数据来自url localhost/myproject/output/names
。
HTML
JS
$(function() { $( "#search" ).autocomplete({ source: "localhost/myproject/output/names" }); });
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"]
或者具有label
和value
属性的对象数组,例如:
[ { label: "name", value: "John Smith" }, { label: "name", value: "Juan dela Cruz" }... ]
如果您的数据源不是以这种格式直接发送数据,您可以将函数传递给source
选项,在该选项中您可以从数据源检索数据并相应地修改它。
该函数接收两个参数:
- 具有单个
term
属性whoes值的请求对象是用户输入 - 一个回调函数,您应该以正确的格式传递数据。
尝试一下
$(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 } }); } }); });
附注:代码未经过测试,仅用于概述。