AJAX实现类似Google的搜索提示
原文:http://www.cnblogs.com/Ferry/archive/2008/12/24/1361505.html
功能就不用多说了,到http://www.google.cn/去试一下就知道了。本例是参考了《征服AJAX》 一书中的范例。
功能就不用多说了,到http://www.google.cn/去试一下就知道了。本例是参考了《征服AJAX》 一书中的范例。
实现该功能也是用到两个页面,一个请求显示(这次使用的静态页面),一个用于获取关键字到数据表中模糊查询并获取满足条件的数据输出。这里的搜索提示实际上是用div来实现的,C#代码很简单,关键是看明白JavaScript。
Code
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml">
3<head>
4 <title>无标题页</title>
5
6 <script language="javascript" type="text/javascript">
7 <!--
8 var searchReq = createReq();
9 /**//* 创建XMLHttpRequest的第一种方法
10 try{
11 searchReq = new ActiveXObject('Msxml2.XMLHTTP');
12 }
13 catch(e){
14 try{
15 searchReq = new ActiveXObject('Microsoft.XMLHTTP');
16 }
17 catch(e){
18 try{
19 searchReq = new XMLHttpRequest();
20 }
21 catch(e)
22 {}
23 }
24 }
25 */
26 //创建XMLHttpRequest的第二种方法
27 function createReq(){
28 var httpReq;
29
30 if(window.XMLHttpRequest){
31 httpReq = new XMLHttpRequest();
32 if(httpReq.overrideMimeType){
33 httpReq.overrideMimeType('text/xml');
34 }
35 }
36 else if(window.ActiveXObject){
37 try{
38 httpReq = new ActiveXObject('Msxml2.XMLHTTP');
39 }
40 catch(e){
41 try{
42 httpReq = new ActiveXObject('Microsoft.XMLHTTP');
43 }
44 catch(e){
45 }
46 }
47 }
48 return httpReq;
49 }
50 //发送HTTP请求,当输入框的内容变化时,会调用该函数
51 function searchSuggest(){
52 var str = escape(document.getElementById("txtSearch").value);
53 searchReq.open("get","Server.aspx?searchText="+str,true);
54 searchReq.onreadystatechange = handleSearchSuggest;
55 searchReq.send(null);
56 }
57
58 //当 onreadystatechange 值变化时,会调用该函数
59 //注意searchSuggest()中的这一句searchReq.onreadystatechange = handleSearchSuggest;
60 function handleSearchSuggest(){
61 if(searchReq.readyState == 4){
62 if(searchReq.status == 200){
63 var suggestText = document.getElementById("search_suggest");
64 var sourceText = searchReq.responseText.split("\n");
65 if(sourceText.length>1){
66 suggestText.style.display="";
67 suggestText.innerHTML = "";
68 for(var i=0;i<sourceText.length-1;i++) {
69 var s='<div onmouseover="javascript:suggestOver(this);"';
70 s+=' onmouseout="javascript:suggestOut(this);" ';
71 s+=' onclick="javascript:setSearch(this.innerHTML);" ';
72 s+=' class="suggest_link">' +sourceText[i]+'</div>';
73 suggestText.innerHTML += s;
74 }
75 }
76 else{
77 suggestText.style.display="none";
78 }
79 }
80 }
81 }
82
83 function suggestOver(div_value){
84 div_value.className = "suggest_link_over";
85 }
86
87 function suggestOut(div_value){
88 div_value.className = "suggest_link";
89 }
90
91 function setSearch(obj){
92 document.getElementById("txtSearch").value = obj;
93 var div = document.getElementById("search_suggest");
94 div.innerHTML = "";
95 div.style.display="none";
96 }
97
98 function tbblur(){
99 var div = document.getElementById("search_suggest");
100 //div.innerHTML = "";
101 div.style.display="none";
102 }
103 //-->
104 </script>
105
106 <style type="text/css" media="screen">
107 body
108 {}{
109 font: 11px arial;
110 }
111 .suggest_link
112 {}{
113 background-color: #FFFFFF;
114 padding: 2px 6px 2px 6px;
115 }
116 .suggest_link_over
117 {}{
118 background-color: #E8F2FE;
119 padding: 2px 6px 2px 6px;
120 }
121 #search_suggest
122 {}{
123 position: absolute;
124 background-color: #FFFFFF;
125 text-align: left;
126 border: 1px solid #000000;
127 }
128 </style>
129</head>
130<body>
131 <div style="width: 500px;">
132 <form id="frm" action="">
133 <input type="text" name="txtSearch" id="txtSearch" onkeyup="searchSuggest();" autocomplete="off" />
134 <input type="submit" name="btnSearch" id="btnSearch" value="搜索" />
135 <br><div id="search_suggest" style="display:none">
136 </div>
137 Welcome to ajax!
138 </form>
139 </div>
140</body>
141</html>
142
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml">
3<head>
4 <title>无标题页</title>
5
6 <script language="javascript" type="text/javascript">
7 <!--
8 var searchReq = createReq();
9 /**//* 创建XMLHttpRequest的第一种方法
10 try{
11 searchReq = new ActiveXObject('Msxml2.XMLHTTP');
12 }
13 catch(e){
14 try{
15 searchReq = new ActiveXObject('Microsoft.XMLHTTP');
16 }
17 catch(e){
18 try{
19 searchReq = new XMLHttpRequest();
20 }
21 catch(e)
22 {}
23 }
24 }
25 */
26 //创建XMLHttpRequest的第二种方法
27 function createReq(){
28 var httpReq;
29
30 if(window.XMLHttpRequest){
31 httpReq = new XMLHttpRequest();
32 if(httpReq.overrideMimeType){
33 httpReq.overrideMimeType('text/xml');
34 }
35 }
36 else if(window.ActiveXObject){
37 try{
38 httpReq = new ActiveXObject('Msxml2.XMLHTTP');
39 }
40 catch(e){
41 try{
42 httpReq = new ActiveXObject('Microsoft.XMLHTTP');
43 }
44 catch(e){
45 }
46 }
47 }
48 return httpReq;
49 }
50 //发送HTTP请求,当输入框的内容变化时,会调用该函数
51 function searchSuggest(){
52 var str = escape(document.getElementById("txtSearch").value);
53 searchReq.open("get","Server.aspx?searchText="+str,true);
54 searchReq.onreadystatechange = handleSearchSuggest;
55 searchReq.send(null);
56 }
57
58 //当 onreadystatechange 值变化时,会调用该函数
59 //注意searchSuggest()中的这一句searchReq.onreadystatechange = handleSearchSuggest;
60 function handleSearchSuggest(){
61 if(searchReq.readyState == 4){
62 if(searchReq.status == 200){
63 var suggestText = document.getElementById("search_suggest");
64 var sourceText = searchReq.responseText.split("\n");
65 if(sourceText.length>1){
66 suggestText.style.display="";
67 suggestText.innerHTML = "";
68 for(var i=0;i<sourceText.length-1;i++) {
69 var s='<div onmouseover="javascript:suggestOver(this);"';
70 s+=' onmouseout="javascript:suggestOut(this);" ';
71 s+=' onclick="javascript:setSearch(this.innerHTML);" ';
72 s+=' class="suggest_link">' +sourceText[i]+'</div>';
73 suggestText.innerHTML += s;
74 }
75 }
76 else{
77 suggestText.style.display="none";
78 }
79 }
80 }
81 }
82
83 function suggestOver(div_value){
84 div_value.className = "suggest_link_over";
85 }
86
87 function suggestOut(div_value){
88 div_value.className = "suggest_link";
89 }
90
91 function setSearch(obj){
92 document.getElementById("txtSearch").value = obj;
93 var div = document.getElementById("search_suggest");
94 div.innerHTML = "";
95 div.style.display="none";
96 }
97
98 function tbblur(){
99 var div = document.getElementById("search_suggest");
100 //div.innerHTML = "";
101 div.style.display="none";
102 }
103 //-->
104 </script>
105
106 <style type="text/css" media="screen">
107 body
108 {}{
109 font: 11px arial;
110 }
111 .suggest_link
112 {}{
113 background-color: #FFFFFF;
114 padding: 2px 6px 2px 6px;
115 }
116 .suggest_link_over
117 {}{
118 background-color: #E8F2FE;
119 padding: 2px 6px 2px 6px;
120 }
121 #search_suggest
122 {}{
123 position: absolute;
124 background-color: #FFFFFF;
125 text-align: left;
126 border: 1px solid #000000;
127 }
128 </style>
129</head>
130<body>
131 <div style="width: 500px;">
132 <form id="frm" action="">
133 <input type="text" name="txtSearch" id="txtSearch" onkeyup="searchSuggest();" autocomplete="off" />
134 <input type="submit" name="btnSearch" id="btnSearch" value="搜索" />
135 <br><div id="search_suggest" style="display:none">
136 </div>
137 Welcome to ajax!
138 </form>
139 </div>
140</body>
141</html>
142
Server.aspx:就是留第一行,把其它删除。
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Server.aspx.cs" Inherits="ajaxPractice.搜索提示S端" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Server.aspx.cs" Inherits="ajaxPractice.搜索提示S端" %>
Server.aspx.cs
Code
1using System;
2using System.Collections;
3using System.Configuration;
4using System.Data;
5using System.Linq;
6using System.Web;
7using System.Web.Security;
8using System.Web.UI;
9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13using System.Data.SqlClient;
14
15namespace ajaxPractice
16{
17 public partial class 搜索提示S端 : System.Web.UI.Page
18 {
19 protected void Page_Load(object sender, EventArgs e)
20 {
21 if (Request.QueryString["searchText"] != null)
22 {
23 if (Request.QueryString["searchText"].ToString().Trim().Length > 0)
24 {
25 #region
26 DataTable dt = new DataTable();
27 using (SqlConnection conn = new SqlConnection(
28 System.Configuration.ConfigurationManager.AppSettings["ConnStr"]))
29 {
30 SqlCommand cmd = new SqlCommand();
31 cmd.Connection = conn;
32 cmd.CommandText = string.Format(
33 "Select BookName From Books Where BookName like '%{0}%'",
34 Request.QueryString["searchText"]);
35 SqlDataAdapter adapter = new SqlDataAdapter(cmd);
36 conn.Open();
37 adapter.Fill(dt);
38 }
39 string returnText = "";
40 if (dt != null && dt.Rows.Count > 0)
41 {
42 for (int i = 0; i < dt.Rows.Count; i++)
43 {
44 returnText += dt.Rows[i][0].ToString() + "\n";
45 }
46 }
47
48 Response.Write(returnText);
49 #endregion
50 }
51 }
52 }
53 }
54}
55
1using System;
2using System.Collections;
3using System.Configuration;
4using System.Data;
5using System.Linq;
6using System.Web;
7using System.Web.Security;
8using System.Web.UI;
9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13using System.Data.SqlClient;
14
15namespace ajaxPractice
16{
17 public partial class 搜索提示S端 : System.Web.UI.Page
18 {
19 protected void Page_Load(object sender, EventArgs e)
20 {
21 if (Request.QueryString["searchText"] != null)
22 {
23 if (Request.QueryString["searchText"].ToString().Trim().Length > 0)
24 {
25 #region
26 DataTable dt = new DataTable();
27 using (SqlConnection conn = new SqlConnection(
28 System.Configuration.ConfigurationManager.AppSettings["ConnStr"]))
29 {
30 SqlCommand cmd = new SqlCommand();
31 cmd.Connection = conn;
32 cmd.CommandText = string.Format(
33 "Select BookName From Books Where BookName like '%{0}%'",
34 Request.QueryString["searchText"]);
35 SqlDataAdapter adapter = new SqlDataAdapter(cmd);
36 conn.Open();
37 adapter.Fill(dt);
38 }
39 string returnText = "";
40 if (dt != null && dt.Rows.Count > 0)
41 {
42 for (int i = 0; i < dt.Rows.Count; i++)
43 {
44 returnText += dt.Rows[i][0].ToString() + "\n";
45 }
46 }
47
48 Response.Write(returnText);
49 #endregion
50 }
51 }
52 }
53 }
54}
55