我想从我的数据库中搜索城市。当用户键入一些首字母时。为此,我使用了以下自动完成 jquery 插件(ASP.Net 3.5 + VS 2008)
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtCity.ClientID%>").autocomplete("Search_CS.ashx");
});
</script>
我的 Search_CS.ashx 课程是,
<%@ WebHandler Language="C#" Class="Search_CS" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection con = DataSetClass.conDB())
{
//con.ConnectionString = ConfigurationManager
// .ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("select DISTINCT cname from City where cname LIKE @CityText + '%'", con))
{
//cmd.CommandText = "select ContactName from Customers where " +
//"ContactName like @SearchText + '%'";
cmd.Parameters.AddWithValue("@CityText", prefixText);
cmd.Connection = con;
StringBuilder sb = new StringBuilder();
//con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["cname"])
.Append(Environment.NewLine);
}
}
con.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
这工作正常,但问题是插件只能工作一次。之后,当我输入姓名首字母时,在我刷新页面之前,自动完成功能不起作用。我尝试了很多解决方案,但都是徒劳的。请帮帮我,因为我从 2 周开始就被困在这里。