基于ajax的简单搜索实现方法
本文实例讲述了基于ajax的简单搜索实现方法。分享给大家供大家参考,具体如下:
这里使用两个.aspx文件,一个叫Default.aspx,一个叫AjaxOperations.aspx,第一个用来输入搜索数据,后一个用来对搜索关键字进行处理。js文件夹下面还有一个testJs.js的文件,它就是ajax操作的核心部分。不错,codeischeap。看代码:
testJs.js
//此函数等价于document.getElementById/document.all
function$(s){if(document.getElementById){returneval('document.getElementById("'+s+'")');}else{returneval('document.all.'+s);}}
//创建XMLHttpRequest对象,以发送ajax请求
functioncreateXMLHTTP(){
varxmlHttp=false;
vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for(vari=0;i<arrSignatures.length;i++){
try{
xmlHttp=newActiveXObject(arrSignatures[i]);
returnxmlHttp;
}
catch(oError){
xmlHttp=false;//ignore
}
}
//thrownewError("MSXMLisnotinstalledonyoursystem.");
if(!xmlHttp&&typeofXMLHttpRequest!='undefined'){
xmlHttp=newXMLHttpRequest();
}
returnxmlHttp;
}
functionaddAjaxSearch(){
inputField=$("txtSearch");
completeTable=$("suggestTb");
completeDiv=$("popup");
completeBody=$("suggestBody");
vartempStr=inputField.value;
//alert(tempStr);
varkeyWord=encodeURI(tempStr);
if(tempStr=="")
return;
varxmlReq=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("Connecttheserverfailed!");
}
}
}
xmlReq.send(null);
}
//设置div中的表格数据
functionsetNames(names){
if(names==""){
clearNames();
return;
}
clearNames();//清空div中已有的的表格数据
setOffsets();//设置div到合适的位置
varrow,cell,txtNode;
vars=names.split("#");
for(vari=0;i<s.length;i++){//显示类似search下拉选择项
varnextNode=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中已有的的表格数据
functionclearNames(){
completeBody=$("suggestBody");
varind=completeBody.childNodes.length;
for(vari=ind-1;i>=0;i--){
completeBody.removeChild(completeBody.childNodes[i]);
}
completeDiv=$("popup");
completeDiv.style.border="none";
}
//设置div到合适的位置
functionsetOffsets(){
completeTable.style.width=inputField.offsetWidth;+"px";
varleft=calculateOffset(inputField,"offsetLeft");
vartop=calculateOffset(inputField,"offsetTop")+inputField.offsetHeight;
completeDiv.style.border="black1pxsolid";
completeDiv.style.left=left+"px";
completeDiv.style.top=top+"px";
}
functioncalculateOffset(field,attr){
varoffset=0;
while(field){
offset+=field[attr];
field=field.offsetParent;
}
returnoffset;
}
//搜索框设置为选择的数据
functioncompleteField(cell){
inputField.value=cell.firstChild.nodeValue;//搜索框设置为选择的数据
clearNames();//清空div中已有的的表格数据
}
//用来设置当鼠标失去焦点后文本框的隐藏
document.onmousedown=function(){
if(!event.srcElement.pop)
clearNames();
}//填写输入框
Default.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="WebTest2008.Default"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title>AjaxSearch</title>
<scriptsrc="js/testJs.js"type="text/javascript"></script>
<styletype="text/css"media="screen">
body
{
font:11pxarial;
}
.suggest_link
{
background-color:#FFFFFF;
padding:2px0px2px0px;
border:solid1px#cceeff;
}
.suggest_link_over
{
background-color:#E8F2FE;
padding:2px0px2px0px;
}
#search_suggest
{
position:absolute;
background-color:#FFFFFF;
text-align:left;
border:1pxsolid#000000;
}
</style>
</head>
<body>
<inputname="txtSearch"id="txtSearch"type="text"class="suggest_link"onkeyup="addAjaxSearch();"maxlength="200"style="width:200px"/>
<inputtype="submit"id="cmdSearch"name="cmdSearch"value="Search"title="RunSearch"/>
<divid="popup"style="position:absolute">
<tableid="suggestTb"cellspacing="0"cellpadding="0"bgcolor="#fffafa"border="0">
<tbodyid="suggestBody">
</tbody>
</table>
</div>
</body>
</html>
Default.aspx.cs:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespaceWebTest2008
{
publicpartialclassDefault:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
}
}
AjaxOperations.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="AjaxOperations.aspx.cs"Inherits="WebTest2008.AjaxOperations"%>
AjaxOperations.aspx.cs:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespaceWebTest2008
{
publicpartialclassAjaxOperations:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!string.IsNullOrEmpty(Request["searchKeyword"]))
{
stringtempStr=Request["searchKeyword"];
/*测试用实际项目中可以对数据库进行检索等等相关操作,这里简化了*/
System.Text.StringBuildersb=newSystem.Text.StringBuilder();
sb.Append(tempStr+"#");
sb.Append("#");
sb.Append(tempStr+=""+tempStr);
sb.Append("#");
sb.Append(tempStr+=""+tempStr);
Response.Write(sb.ToString().TrimEnd(newchar[]{'#'}));
}
}
}
}
上面的代码我都已经测试通过,复制粘贴运行试试看吧。
刚看到一篇文章里说,“实时搜索带来的痛苦要远大于他带来的帮助。这就是为什么GoogleSuggest还处于beta测试而并没有放在主页上的原因。在Start.comLive.com上搜索的时候你是不能使用返回按钮来查看上一次搜索或返回上一页的。或许还没有人来完成这项工作,但是完成这个工作应该是很困难的至少是不太明知的或者会因此带来更多的麻烦。(译注:现在已经有很多开源的框架可以实现历史记录功能)”。其实ajax实时搜索还是很有吸引力的,现在的很多网站都有这个功能。学习一下还是很有意义的。
希望本文所述对大家ajax程序设计有所帮助。