所以假设我有一个json对象,我从asmx文件/ web服务文件中获取。
[
{
"UserName": "hl",
"FirstName": "hendra",
"LastName": "lim"
},
{
"UserName": "wd",
"FirstName": "wildan",
"LastName": "dan"
},
{
"UserName": "gd",
"FirstName": "genin",
"LastName": "gn"
},
{
"UserName": "tr",
"FirstName": "tere",
"LastName": "magda"
}
]
当我尝试访问它时,我这样做:
$("#tags").autocomplete({
source: availableTags,
focus: function (event, ui) {
$("#tags").val(ui.item.FirstName);
return false;
},
select: function (event, ui) {
$("#tags").val(ui.item.FirstName);
return false;
}
});
你知道吗?它不起作用......这让我头疼了2天。但后来我将我的json对象更改为:
[{"label": "hendra", "value": "hl"},
{"label":"wildan", "value": "wd"},
{ "label": "genin", "value": "gn"},
{"label": "hendrik", "value": "hdrik"}]
$("#tags").autocomplete({
source: availableTags,
focus: function (event, ui) {
$("#tags").val(ui.item.label);
$('#key').val(ui.item.value);
return false;
},
select: function (event,ui){
$('#tags').val(ui.item.label);
$('#key').val(ui.item.value);
return false;
}
});
这是有效的,但是现在我想知道为什么当我使用第一种方法时,为什么jquery自动完成功能不起作用,浪费我的时间2天并且让他们非常头痛地想出来,但仍然无法得到它,jquery如果我使用
,则无法正常工作ui.item.FirstName
但它与
一起使用ui.item.label or ui.item.value
我的第一种方法有问题吗?我认为它与第二个几乎相同,唯一不同的是在json对象中,一个使用“UserName,FirstName等”,另一个使用“label,and value”。
答案 0 :(得分:0)
试试这个......你必须使用
$.each(data, function(key, value) { LocalityArray[key] = value.LocalityName; });
我的例子。
function GetLocalityList() {
var LocalityArray = [];
$.post("MvcLayer/Index/GetLocalityList",
{
CityID: $('#sltCity').val()
},
function(data) {
// My sql query will be like this select LocalityID, CityID, LocalityName from tablename where CityID = 20
// Here (data) is array format. Like this
// [{"LocalityID":9397,"CityID":55,"LocalityName":"Adugodi"},{"LocalityID":9398,"CityID":55,"LocalityName":"Aga Abbas Ali Road"},{"LocalityID":9399,"CityID":55,"LocalityName":"Agaram"},{"LocalityID":9400,"CityID":55,"LocalityName":"Agrahara Dasara Halli"},{"LocalityID":9401,"CityID":55,"LocalityName":"Agrahara Dasarahalli"},{"LocalityID":9402,"CityID":55,"LocalityName":"Airport Exit Road"},{"LocalityID":9403,"CityID":55,"LocalityName":"Horamavu"},{"LocalityID":9404,"CityID":55,"LocalityName":"Hosakere Halli"},{"LocalityID":9405,"CityID":55,"LocalityName":"Hennur"},{"LocalityID":9406,"CityID":55,"LocalityName":"Hesaraghatta"},{"LocalityID":9407,"CityID":55,"LocalityName":"HKP Road"},{"LocalityID":9408,"CityID":55,"LocalityName":"HMT Layout"},{"LocalityID":9409,"CityID":55,"LocalityName":"Hongasandra"},{"LocalityID":9410,"CityID":55,"LocalityName":"Hoody"},{"LocalityID":9411,"CityID":55,"LocalityName":"Hayes Road"} ]
$.each(data, function(key, value) {
LocalityArray[key] = value.LocalityName;
});
$("#txtLocality").autocomplete({
minLength: 1,
source: LocalityArray
});
},
'json'
);
}