ASP.NET jQuery 食谱25 (使用jQuery UI的Autocomplete方法实现文本框的自动搜索填充功能)

这节将使用jQuery UI的Autocomplete方法实现文本框的自动搜索填充功能,并且这里会使用另外一个方法来实现AJAX调用服务器方法,就是通过ASP.NET HTTP handler来处理请求的数据。现在就来看下实现的步骤:

1.创建SearchKeys.ashx请求处理文件,并实现以下代码:

<%@ WebHandler Language="C#" Class="SearchKeys" %>

using System;
using System.Web;

// 添加两个命名空间
using System.Collections.Generic;
using System.Web.Script.Serialization;

public class SearchKeys : IHttpHandler {

/// <summary>
/// 根据关键字过滤内容
/// </summary>
/// <param name="keyword">关键字</param>
/// <returns>过滤数组</returns>
private string[] GetFilteredList(string keyword)
{
List<string> countryList = new List<string>();
countryList.Add("阿联酋");
countryList.Add("阿富汗");
countryList.Add("阿尔巴利亚");
countryList.Add("阿鲁巴");
countryList.Add("巴西");
countryList.Add("亚美利亚");
countryList.Add("西班牙");

List<string> filteredList = new List<string>();

foreach (string sCountry in countryList)
{
// 判断是否包含关键字的国家,然后加入到过滤后的集合中。
if (sCountry.Contains(keyword))
{
filteredList.Add(sCountry);
}
}

// 返回数组,以便后面能序列化为JSON格式数据
return filteredList.ToArray();
}

public void ProcessRequest(HttpContext context)
{
string keyword = context.Request.QueryString["keyword"];

if (keyword != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();

// 通过JavaScriptSerializer对象的Serialize序列化为["value1","value2",...]的字符串
string jsonString = serializer.Serialize(GetFilteredList(keyword));

context.Response.Write(jsonString); // 返回客户端json格式数据
}
}

public bool IsReusable {
get {
return false;
}
}

}

2.创建页面文件Recipe25.aspx,页面代码(HTML部分)如下:

<body>
<form id="form1" runat="server">
<div align="center">
<fieldset style="width: 400px; height: 100px;">
<table border="0" cellpadding="3" cellspacing="3">
<tr>
<td>
<asp:Label ID="lblCountry" runat="server">国家:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtSearch" runat="server" Width="150px"></asp:TextBox>
</td>
</tr>
</table>
</fieldset>
</div>
</form>
</body>

3.页面文件Recipe25.aspx的脚本代码实现如下:(如何获取和引入jQuery UI已经在前面章节讲过,这里就不用重复了)

  <link type="text/css" rel="Stylesheet" href="../Styles/sunny/jquery-ui-1.8.17.custom.css" />
<script type="text/javascript" src="../Scripts/jquery.js"></script>
<script type="text/javascript" src="../Scripts/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript">
$(
function () {
$(
"#txtSearch").autocomplete({
minLength:
1, // 设置搜索的关键字最小长度
// 设置自动完成列表的函数,函数包括两个参数,requset和response
source: function (request, response) {
$.ajax({
type:
"POST",
// 通过request.term可以获得文本框内容
url: "SearchKeys.ashx?keyword=" + request.term,
contentType:
"application/json; charset=utf-8",
dataType:
"json",
success:
function (data) {
// jQuery.map(array, callback) :将一个数组中的元素转换到另一个数组中。
// 下面就是把数组["value1", "value2",...]转换为[{value:"value1"}, {value:"value2"},...]
response($.map(data, function (item) {
return { value: item };
}));
},
error:
function () {
alert(
"ajax请求失败");
}
});
}
});
});
</script>

4.实现效果图:

5.分析XmlHttpRequest对象,请求参数和响应数据如下:

posted @ 2012-02-17 21:51  PyCoder  阅读(5584)  评论(8编辑  收藏  举报