1.首页页面添加如下代码
<link type="text/css" href="JS/redmond/jquery-ui-1.8.7.custom.css" rel="stylesheet" />
<script type="text/javascript" src="JS/jquery-1.4.1.js"></script>
<script type="text/javascript" src="JS/jquery-ui-1.8.7.custom.min.js"></script>
<script type="text/javascript" language="javascript">
$(function() {
function setMes(message) {
$("#txt1")[0].innerText = message; //Ajax请求数据回调后给控件扶植
}
debugger;
$('#<%=TextBox1.ClientID %>').autocomplete({ //TextBox1这是服务器端控件,使用HTML控件同样可以;不过建议使用HTML控件
source: function(request, response) { //请求的数据源
$.ajax({
url: "autocompletePage.aspx",
dataType: "json", //请求的数据格式
data: {
term: request.term //这个就是传到请求页面的值,其实就在文本框里输入的文本
},
success: function(data) { //这个就是ajax请求成功的状态,它能够响应一个回调函数,从请求页面返回的数据就是data,可以使用任何字符代替
if (data != null) {
response($.map(data, function(item) { //这里是吧返回的数据根据return的规则进行格式化
return {
key: item.key,
value: item.value
}
}));
}
else
{
return response(""); //这个就是当没有结果时就清除弹出层的内容
}
}
});
},
select: function(event, result) { //这是当选了弹出层所触发的事件
if (result.item != null) {
var text = result.item.value; //这个就是选中的值
setMes(text);
}
else {
$("#txt1").innerText = '';
}
}
});
});
2.在请求页面构造函数(使用数组或集合装数据,构造json格式的数据)
public partial class autocompletePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ResponseData();
}
//构造数组和集合道理是一样的哈
private void ResponseData()
{
Product[] pms = GetArray().Where(c => c.Name == Text).ToArray();
string str = "";
if (pms.Length > 0)
{
str = "[";
foreach (Product item in pms)
str += "{\"key\":\"" + item.ID + "\",\"value\":\"" + item.Name + "\"},";
str = str.Substring(0, str.Length - 1);
str += "]";
}
Response.Clear(); //注意这部分是能否返回数据的关键
Response.Charset = "utf-8";
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentType = "application/json;charset=UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(str);
Response.Flush();
Response.Close();
}
public Product[] GetArray()
{
Product[] p = new Product[5];
p[0] = new Product();
p[0].ID = "1";
p[0].Name = "苹果";
p[1] = new Product();
p[1].ID = "2";
p[1].Name = "香蕉";
p[2] = new Product();
p[2].ID = "3";
p[2].Name = "菠萝";
p[3] = new Product();
p[3].ID = "4";
p[3].Name = "菠萝";
p[4] = new Product();
p[4].ID = "5";
p[4].Name = "菠萝";
return p;
}
public List<Product> GetList()
{
List<Product> plist = new List<Product> { new Product { ID = "1", Name = "苹果" },
new Product { ID = "2", Name = "香蕉" }, new Product { ID = "3", Name = "菠萝" } };
return plist;
}
public string Text
{
get { return Request["term"]; }
}
}
public class Product
{
public string ID{get;set;}
public string Name { get; set; }
}