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

[转载]ASP.NET jQuery 食谱25 (使用jQuery UI的Autocomplete方法实现文本框的自动搜索填充功能) - KenLee - 博客园.

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

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

using System;
using System.Web;

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

public class SearchKeys : IHttpHandler {

///

<summary> /// 根据关键字过滤内容
/// </summary>

&nbsp;

///关键字 /// 过滤数组
private string[] GetFilteredList(string keyword)
{
List countryList = new List();
countryList.Add("阿联酋");
countryList.Add("阿富汗");
countryList.Add("阿尔巴利亚");
countryList.Add("阿鲁巴");
countryList.Add("巴西");
countryList.Add("亚美利亚");
countryList.Add("西班牙");

ListfilteredList = new List();

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;
}
}

}
[/csharp]
2.创建页面文件Recipe25.aspx,页面代码(HTML部分)如下:
[html]

<form id="form1">
<div align="center">
<fieldset style="width: 400px; height: 100px;">
<table border="0" cellspacing="3" cellpadding="3">
<tbody>
<tr>
<td>国家:</td>
<td></td>
</tr>
</tbody>
</table>
</fieldset>
</div>
</form>
[/html]
3.页面文件Recipe25.aspx的脚本代码实现如下:(如何获取和引入jQuery UI已经在前面章节讲过,这里就不用重复了)
[js]
<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">// <![CDATA[
$(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>
[/js]

4.实现效果图:

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