本文執行個體講述了基於ajax的簡單搜尋實現方法。分享給大家供大家參考,具體如下:
這裡使用兩個.aspx檔案,一個叫Default.aspx,一個叫AjaxOperations.aspx,第一個用來輸入搜尋資料,後一個用來對搜尋索引鍵進行處理。js檔案夾下面還有一個testJs.js的檔案,它就是ajax操作的核心部分。不錯,code is cheap。看代碼:
testJs.js
// 此函數等價於document.getElementById /document.allfunction $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }// 建立 XMLHttpRequest對象,以發送ajax請求 function createXMLHTTP() { var xmlHttp = false; var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < arrSignatures.length; i++) { try { xmlHttp = new ActiveXObject(arrSignatures[i]); return xmlHttp; } catch (oError) { xmlHttp = false; //ignore } } // throw new Error("MSXML is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp;}function addAjaxSearch() { inputField = $("txtSearch"); completeTable = $("suggestTb"); completeDiv = $("popup"); completeBody = $("suggestBody"); var tempStr = inputField.value; // alert(tempStr); var keyWord = encodeURI(tempStr); if (tempStr == "") return; var xmlReq = createXMLHTTP(); xmlReq.open("post", "AjaxOperations.aspx?searchKeyword=" + keyWord, true); xmlReq.onreadystatechange = function() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { //xmlReq.responseText為輸出的那段字串 setNames(xmlReq.responseText); } else { alert("Connect the server failed!"); } } } xmlReq.send(null);}// 設定div中的表格式資料function setNames(names) { if (names == "") { clearNames(); return; } clearNames(); // 清空div中已有的的表格式資料 setOffsets(); // 設定div到合適的位置 var row, cell, txtNode; var s = names.split("#"); for (var i = 0; i < s.length; i++) { // 顯示類似search下拉選擇項 var nextNode = s[i]; row = document.createElement("tr"); cell = document.createElement("td"); cell.onmouseout = function() { this.style.backgroundColor = ''; }; cell.onmouseover = function() { this.style.backgroundColor = '#E8F2FE'; }; cell.onclick = function() { completeField(this); }; // 搜尋方塊設定為選擇的資料 cell.pop = "T"; txtNode = document.createTextNode(nextNode); cell.appendChild(txtNode); row.appendChild(cell); $("suggestBody").appendChild(row); }}// 清空div中已有的的表格式資料function clearNames() { completeBody = $("suggestBody"); var ind = completeBody.childNodes.length; for (var i = ind - 1; i >= 0; i--) { completeBody.removeChild(completeBody.childNodes[i]); } completeDiv = $("popup"); completeDiv.style.border = "none";}// 設定div到合適的位置function setOffsets() { completeTable.style.width = inputField.offsetWidth; +"px"; var left = calculateOffset(inputField, "offsetLeft"); var top = calculateOffset(inputField, "offsetTop") + inputField.offsetHeight; completeDiv.style.border = "black 1px solid"; completeDiv.style.left = left + "px"; completeDiv.style.top = top + "px";}function calculateOffset(field, attr) { var offset = 0; while (field) { offset += field[attr]; field = field.offsetParent; } return offset;}// 搜尋方塊設定為選擇的資料function completeField(cell) { inputField.value = cell.firstChild.nodeValue; // 搜尋方塊設定為選擇的資料 clearNames(); //清空div中已有的的表格式資料}//用來設定當滑鼠失去焦點後文字框的隱藏document.onmousedown = function() { if (!event.srcElement.pop) clearNames();} //填寫輸入框
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest2008.Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>Ajax Search</title> <script src="js/testJs.js" type="text/javascript"></script> <style type="text/css" media="screen"> body { font: 11px arial; } .suggest_link { background-color: #FFFFFF; padding: 2px 0px 2px 0px; border:solid 1px #cceeff; } .suggest_link_over { background-color: #E8F2FE; padding: 2px 0px 2px 0px; } #search_suggest { position: absolute; background-color: #FFFFFF; text-align: left; border: 1px solid #000000; } </style></head><body> <input name="txtSearch" id="txtSearch" type="text" class="suggest_link" onkeyup="addAjaxSearch();" maxlength="200" style="width: 200px" /> <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" title="Run Search" /> <div id="popup" style="position: absolute"> <table id="suggestTb" cellspacing="0" cellpadding="0" bgcolor="#fffafa" border="0"> <tbody id="suggestBody"> </tbody> </table> </div></body></html>
Default.aspx.cs:
using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebTest2008{ public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }}
AjaxOperations.aspx:
複製代碼 代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxOperations.aspx.cs" Inherits="WebTest2008.AjaxOperations" %>
AjaxOperations.aspx.cs:
using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebTest2008{ public partial class AjaxOperations : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["searchKeyword"])) { string tempStr = Request["searchKeyword"]; /* 測試用 實際項目中可以對資料庫進行檢索等等相關操作,這裡簡化了 */ System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(tempStr + " #"); sb.Append("#"); sb.Append(tempStr += " " + tempStr); sb.Append("#"); sb.Append(tempStr += " " + tempStr); Response.Write(sb.ToString().TrimEnd(new char[] { '#' })); } } }}
上面的代碼我都已經測試通過,複製粘貼運行試試看吧。
剛看到一篇文章裡說,“即時搜尋帶來的痛苦要遠大於他帶來的協助。這就是為什麼Google Suggest還處於beta測試而並沒有放在首頁上的原因。在Start.com Live.com上搜尋的時候你是不能使用返回按鈕來查看上一次搜尋或返回上一頁的。或許還沒有人來完成這項工作,但是完成這個工作應該是很困難的至少是不太明知的或者會因此帶來更多的麻煩。(譯註:現在已經有很多開源的架構可以實現記錄功能)”。其實ajax即時搜尋還是很有吸引力的,現在的很多網站都有這個功能。學習一下還是很有意義的。
希望本文所述對大家ajax程式設計有所協助。