如何使用获取的json数据使用JQuery UI自动完成? 它不适用于我的。
我使用这个例子https://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
选项,在该选项中您可以从数据源检索数据并相应地修改它。
该函数接收两个参数:
尝试一下
$(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 } }); } }); });
附注:代码未经过测试,仅用于概述。
以上就是jQuery教程分享使用JQuery UI自动完成function从JSON搜索数据无法正常工作相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/532254.html