使用JQuery UI自动完成不工作的JSON数据搜索 [英] Searching data from JSON using JQuery UI autocomplete not working
问题描述
我如何使用获取使用JSON数据JQuery用户界面自动完成?它不工作对矿井。
How can I use JQuery UI autocomplete using fetched json data? It's not working on mine.
我用这个例子 http://jqueryui.com/autocomplete/ ,而不是硬codeD数据,我从JSON获取。
I use this example http://jqueryui.com/autocomplete/, but instead of hard-coded data I fetch from json.
我的JSON数据是从网址本地主机/ myproject的/输出/名称
。
My json data is from a 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"}]
修改
我已经设法与JSON数据修复该问题由@artm评论。现在是 [{约翰·史密斯},{胡安·德拉克鲁兹}]
I already manage to fix the issue with json data as commented by @artm. now it's [{John Smith},{Juan dela Cruz}]
但另一个问题是,当我键入字母 0
两个两个的建议即使只有约翰·史密斯
包含 0
。我该如何解决这个问题?
But another problem is, when I type the letter o
both of the two is suggested even though only John Smith
contains o
. How can I fix this?
推荐答案
在jQuery用户界面自动完成预计无论是字符串数组,例如:
The jQuery UI autocomplete expects either an array of strings, for example
["John Smith", "Juan dela Cruz"]
或有对象的数组标签
和值
属性,例如:
Or an array of objects having label
and value
properties, for example:
[ { label: "name", value: "John Smith" }, { label: "name", value: "Juan dela Cruz" }... ]
在情况下,如果您的数据源不直接以这种格式发送数据,你可以传递一个函数来的 源
选项,在其中您可以从数据源中检索数据,并相应修改。
In case if your data source is not directly sending data in this format, you can pass a function to the source
option, in which you can retrieve data from the data source and modify it accordingly.
这个函数接收两个参数:
The function receives two arguments:
- 单
项请求对象
属性whoes值是用户输入 - 的回调函数,你应该通过正确的格式的数据。
- A request object with single
term
property whoes value is the user input - A callback function to which you should pass the data in correct format.
尝试沿着
$(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
}
});
}
});
});
边注:code未测试,它只是给了一个全面的介绍。
Side note: The code is not tested and it is just for giving a broad overview.
这篇关于使用JQuery UI自动完成不工作的JSON数据搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!