服务器端后台代码:

 1          private string GetModelNames() {
2 return @"[
3 {
4 'value': 'jquery',
5 'label': 'jQuery',
6 'desc': 'the write less, do more, JavaScript library',
7 },
8 {
9 'value': 'jquery-ui',
10 'label': 'jQuery UI',
11 'desc': 'the official user interface library for jQuery',
12 },
13 {
14 'value': 'sizzlejs',
15 'label': 'Sizzle JS',
16 'desc': 'a pure-JavaScript CSS selector engine',
17 }
18 ]".Replace("'", "\"");
19 }

第一种方式:动态数据源

Aspx页面代码:

                $("#ModelName2").autocomplete({
minLength: ,
source:function( request, response ) {
$.ajax({
url: "SystemAjaxData.ashx?selectType=getModelNames",
success: function (data) {
var jsonData = eval("(" + data + ")");
response(jsonData);
}
});
},
focus: function (event, ui) {
$("#ModelName2").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#ModelName2").val(ui.item.label);
$("#ModelNameValue2").val(ui.item.value); return false;
}
});

由于Ajax返回的是字符串,因此必须用eval方法转换成Json对象再返回给Autocomplete插件使用。

第二种方式:固定数据源方式,并且动态改变下拉选择框样式

      var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
]; $("#ModelName2").autocomplete({
minLength: ,
source:projects,
focus: function (event, ui) {
$("#ModelName2").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#ModelName2").val(ui.item.label);
$("#ModelNameValue2").val(ui.item.value); return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
};

第三种方式:缓存后台数据源

 var cache = {};
$("#ModelName2").autocomplete({
minLength: ,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.ajax({
url: "SystemAjaxData.ashx?selectType=getModelNames",
success: function (data) {
var jsonData = eval("(" + data + ")");
cache[ term ]=jsonData;
response(jsonData);
}
});
},
focus: function (event, ui) {
$("#ModelName2").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#ModelName2").val(ui.item.label);
$("#ModelNameValue2").val(ui.item.value); return false;
}
});
05-07 15:56
查看更多