使用JSON jQuery UI的自动完成 [英] jQuery UI autocomplete with JSON
问题描述
好吧被伤透我对这个大脑(在这个可怕的即时消息),但香港专业教育学院啊阅读试过所有我可以和斜面仍然得到它的工作。
Alright been racking my brain on this (im terrible at this) but yea ive tried reading all i can and still cant get it to work.
试图做自动完成与jQuery UI的
trying to do autocomplete with jquery ui
我的JSON看起来像这样
my json looks like this
{"dealers":
{
"1156":"dealer 1",
"1122":"dealer 2",
"1176":"dealer 3",
"1491":"dealer 4",
"1463":"dealer 5",
"269":"dealer 6"
}
}
我将尝试使用此信息为源自动完成。我得到的响应对象就好了,我只是遇到麻烦在正确的格式,以便我可以将###在一个隐藏字段绑在值需要被显示的部分降了下来。
i am trying to use this information as the source for autocomplete. i am getting the response object just fine I am just having trouble getting it in the right format so that I can place the "###" in a hidden field tied to the "value" which needs to be displayed as the portion of the drop down.
一直在尝试一百万个不同的方法,但最近一次低于
been trying a million different ways but a recent attempt was below
function ajaxCall() {
$.getJSON("/example/location/example.json?term=" + $('#dealerName').val(), function(data) {
$.each(data.dealers, function(k, v) {
alert(k + ' : ' + v);
});
});
}
$('#dealerName').autocomplete({
source: ajaxCall,
minLength: 2,
delay: 100
});
请和谢谢了!
推荐答案
您需要改变你正在回在jQueryUI的预期格式的数组对象。
You need to transform the object you are getting back into an array in the format that jQueryUI expects.
您可以使用 $。图
改造代理商
对象转换成数组。
You can use $.map
to transform the dealers
object into that array.
$('#dealerName').autocomplete({
source: function (request, response) {
$.getJSON("/example/location/example.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
请注意,当你选择一个项目,钥匙将被放置在文本框中。您可以通过调整标签
和值
属性 $。图$更改此C $ C>的回调函数返回。
Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label
and value
properties that $.map
's callback function return.
另外,如果你有机会获得服务器端code,它正在生成JSON,你可以改变返回数据的方式。只要数据
Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:
- 是有一个
标签对象的数组
属性,一个值
属性,或两者兼而有之,或 - 是一个简单的字符串数组
- Is an array of objects that have a
label
property, avalue
property, or both, or - Is a simple array of strings
在换句话说,如果你可以格式化数据是这样的:
In other words, if you can format the data like this:
[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
或本
["dealer 5", "dealer 6"]
那么你的JavaScript变得简单多了:
Then your JavaScript becomes much simpler:
$('#dealerName').autocomplete({
source: "/example/location/example.json"
});
这篇关于使用JSON jQuery UI的自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!