页面代码
<html> <head> <title> </title> <%--导入javascript库--%> <script type="text/javascript" src="http://us03.lockview.cn/Js/lockview.js?uid=LK5346096"></script> <script type="text/javascript"> function divShow() { <%--判断输入的是否为空 如果为空则隐藏div 如果不为空则显示div --%> if ($("#tbxSearchKeywords").val() == "") { document.getElementById("divshow").style.display = "none"; } else { document.getElementById("divshow").style.display = "inherit"; //编写Ajax的方法 $.ajax({ //提交方式为Get type: "get", //访问的handler地址 参数d=" + new Date()是为了防止缓存是他每次访问的参数不同 url: "../DivHanadler.ashx?d=" + new Date(), //设置提交的参数 data: { name: $("#tbxSearchKeywords").val(), seach: $("#ddlSearchType").val() }, //提交的方式是json提交 dataType: "json", //如果成功则得到返回的结果然后用javascript库中的each方法遍历返回的json集合 success: function (data) { var selectData = data.selectData; var html = ""; //用each遍历json集合 $.each(selectData, function (i, dataitem) { html = html + dataitem.item + "<br/>"; }); $("#divshow").html(html); }, //如果失败的话则弹出错误提醒 error: function (data) { alert(data.responseText); } }); } } </script> </head> <body> <table> <tr> <td width="315" align="left" valign="middle"> <input id="tbxSearchKeywords" name="textfield" type="text" class="txt" value="" style=" 300px;" onkeyup="divShow()" /> <div id="divshow" style="position: absolute; 305px; height: 300px; display: none; border: 1px solid #abe1dc; background-color: white;"> </div> </td> </tr> </table> </body> </html>
handler中的代码
using System; using System.Collections.Generic; using System.Web; using System.Data.SqlClient; using System.Data; using System.Text; using System.Web.SessionState; namespace ZMStore { /// <summary> /// DivHanadler 的摘要说明 /// </summary> public class DivHanadler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { //得到请求的参数 string name = context.Request["name"].ToString(); //编写连接字符串 string conStr = "Data Source=.;Initial Catalog=sq_hceis1120;Integrated Security=True"; //创建连接对象 SqlConnection conn = new SqlConnection(conStr); //编写查询语句 string sqlStr = "select * from book_item where en_name like '" + name + "%'"; //创建适配器对象 SqlDataAdapter adapter = new SqlDataAdapter(sqlStr, conn); //创建临时表对象 DataTable dt = new DataTable(); //填充数据 adapter.Fill(dt); StringBuilder sb = new StringBuilder(); //讲数据封装成josn对象 sb.Append("{"selectData":["); int count = dt.Rows.Count; //判断查询的结果是否有18条以上 如果超过18条则默认查询前18条 if (dt.Rows.Count > 18) count = 18; for (int i = 0; i < count; i++) { sb.Append("{"item":"" + dt.Rows[i][6].ToString().Replace(""", "").Replace(" ", "").Replace(""", "").Replace(" ", "").Replace(" ", "").Trim() + ""},"); } sb.Remove(sb.Length - 1, 1); sb.Append("]}"); //返回查询结果 context.Response.Write(sb.ToString()); context.Response.End(); } public bool IsReusable { get { return false; } } } }