Home>

For a better user experience,Whether it's desktop software or a website,Tips are added to the search query input,Just like Baidu search! Today the author introduces how to use ajax to implement search information prompt function on asp.net programming.

In usual software development,Searching for information is often encountered,Adding search keyword ideas is a great way to improve the user experience.Today, I will introduce how to use ajax to achieve search information tips in asp.net!

1. Some points to know

(1) Creation of ajax objects in different browsers

Different browsers implement ajax (xmlhttprequest) objects differently.For example, the IE browser implements the Ajax object through the ActiveX control. While other browsers such as Firefox,It implements the ajax object into an object inside the browser called xmlhttprequest, so different browsers create ajax objects differently.So let's look at the way to create ajax objects between different browsers:

Created under ie browser:

  //ie browser
    try {
      //ie5.0
      httprequest=new activexobject ("msxml2.xmlhttp");
    } catch (e) {
      try {
        //ie5.5 and above
        httprequest=new activexobject ("microsoft.xmlhttp");
    } catch (e) {}

Created in Firefox:

//Firefox, safari and other browsers
httprequest=new xmlhttprequest ();

Multi-browser ajax object creation function:

function createajaxobj () {
  var httprequest=false;
  //Judgment whether to include xmlhttprequest object
  if (window.xmlhttprequest) {
    //Firefox, safari and other browsers
    httprequest=new xmlhttprequest ();
    if (httprequest.overridemimetype)
      httprequest.overridemimetype ("text/xml");
  } //Judgment whether to support the active control object
  else if (window.activexobject) {
    //ie browser
    try {
      //ie5.0
      httprequest=new activexobject ("msxml2.xmlhttp");
    } catch (e) {
      try {
        //ie5.5 or more
        httprequest=new activexobject ("microsoft.xmlhttp");
    } catch (e) {}
    }
  }
  //Return the created ajax object
  return httprequest;
}

(2) Use of the event that the content of the text box changes in different browsers

There is currently no standard version of the event where the content of the text box changes.We only care about ie and Firefox,So how do you represent these two times under ie and Firefox?

ie:onpropertychange

firefox:oninput

So how does it work when the page loadsHow about attaching the corresponding change event to the text box according to the browser?

1.js how to determine the browser version

//ie browser
if (navigator.useragent.indexof ("msie")>0)
{}
//Firefox browser
if (isfirefox=navigator.useragent.indexof ("firefox")>0)
{}

2. Attach the corresponding event to the text box according to the browser version

function getos () {
  //Judge the browser type
    if (navigator.useragent.indexof ("msie")>0) {
    //Suppose the text box id is "txtsearch"
    //Append events supported by ie to the text box
    document.getelementbyid ("txtsearch"). attachevent ("onpropertychange", search);
    ostyep="msie";
  } else if (navigator.useragent.indexof ("firefox")>0) {
    //Suppose the text box id is "txtsearch"
    //Attach events supported by Firefox to the text box
    document.getelementbyid ("txtsearch"). addeventlistener ("input", search, false);
    ostyep="firefox";
  }
}

3. Clear the corresponding event for the text box according to the browser version

function clearos () {

if (navigator.useragent.indexof ("msie")>0) {

//Suppose the text box id is "txtsearch"

//Clear events supported by ie for text box

document.getelementbyid ("txtsearch"). detachevent ("onpropertychange", search);

ostyep="msie";

} else if (navigator.useragent.indexof ("firefox")>0) {

//Suppose the text box id is "txtsearch"

//Clear events supported by Firefox for the text box

document.getelementbyid ("txtsearch"). removeeventlistener ("input", search, false);

ostyep="firefox";

}

}

Client design

(1) Analysis of the realization process

After understanding the above knowledge points,Let's take a look at the overall process of implementing search tips:

1) First, the client captures the entered keywords through the text box input event

2) Submit to the server through the ajax object we created before

3) The server accepts the submitted keywords,Perform a query to return the result set to the client for display

The process is as follows:

(2) Writing of style

<style type="text/css" media="screen">
  body
  {
    font:11px arial;
  }
  /* Set the style sheet on the prompt list * /
  .search_link
  {
     background-color:#ffffff;
     cursor:pointer;
     line-height:24px;
     text-indent:6px;
  }
  /* Set the style sheet when the mouse moves to the prompt list * /
  .search_link_over
  {
     background-color:#e8f2fe;
     cursor:pointer;
     line-height:24px;
     text-indent:6px;
  }
  /* Set the style sheet for the search prompt div * /
  #search_div
  {
    position:absolute;
    background-color:#ffffff;
    text-align:left;
    border:1px solid #000000;
    border-top:0px;
    display:none;
    min-width:553px;
    width:553px;
  }
  /* Text box style * /
  .maininput {
  line-height:26px;
  height:28px;
  width:550px;
  font-size:16px;
  font-family:"Microsoft Yahei", "Songti", candara;
  font-weight:normal;
  color:#666;
  margin:auto;
  border:none;
  text-indent:8px;
}
  /* Mouse over text box style * /
  .maininputover {
  width:552px;
  height:30px;
  border-top-width:1px;
  border-right-width:1px;
  border-bottom-width:1px;
  border-left-width:1px;
  border-top-style:solid;
  border-right-style:solid;
  border-bottom-style:solid;
  border-left-style:solid;
  border-top-color:#b7b7b7;
  border-right-color:#d0d0d0;
  border-bottom-color:#d0d0d0;
  border-left-color:#d0d0d0;
}
/* Mouse to leave text box style * /
.maininputfocus {
  width:552px;
  height:30px;
  border:1px solid #41b5f2;
}
/* Click text box style * /
.myborder
{
  width:552px;
  height:30px;
  border-top:1px solid #cccccc;
  border-bottom:1px solid #dddddd;
  border-left:1px solid #dddddd;
  border-right:1px solid #dddddd;
}
  </style>

(3) Writing of aspx pages and ajax_search.js files

The next step is a more important part.The aspx page and the ajax_search.js file include the overall method including display and request.

1. Implementation of the page

<body onload="getos ()" onkeydown="if (event.keycode == 13) return false;">
  <form runat="server">
  <div>
  <div onmouseover="this.classname =" maininputover "" onmouseout="this.classname =" myborder "" onclick="this.classname =" maininputfocus "">
  <input type="text" name="txtsearch" onblur="hiddendiv ()" autocomplete="off" />
  </div>
  <!-The result of this div as a realistic search hint->
  <div></div>
  </div>
  </form>
</body>

2. Create ajax object according to browser

var searchreq=createajaxobj ();
var ostyep="";
function getos () {
  //Judge the browser type
  if (navigator.useragent.indexof ("msie")>0) {
    document.getelementbyid ("txtsearch"). attachevent ("onpropertychange", search);
    ostyep="msie";
  } else if (navigator.useragent.indexof ("firefox")>0) {
    document.getelementbyid ("txtsearch"). addeventlistener ("input", search, false);
    ostyep="firefox";
  }
}
function clearos () {
  if (navigator.useragent.indexof ("msie")>0) {
    document.getelementbyid ("txtsearch"). detachevent ("onpropertychange", search);
    ostyep="msie";
  } else if (navigator.useragent.indexof ("firefox")>0) {
    document.getelementbyid ("txtsearch"). removeeventlistener ("input", search, false);
    ostyep="firefox";
  }
}
function createajaxobj () {
  var httprequest=false;
  //Judgment whether to include xmlhttprequest object
  if (window.xmlhttprequest) {
    //Firefox, safari and other browsers
    httprequest=new xmlhttprequest ();
    if (httprequest.overridemimetype)
      httprequest.overridemimetype ("text/xml");
    //ie:onpropertychange
    //ff:oninput
  } //Determine whether the active control object is supported
  else if (window.activexobject) {
    //ie browser
    try {
      //ie5.0
      httprequest=new activexobject ("msxml2.xmlhttp");
    } catch (e) {
      try {
        //ie5.5 or more
        httprequest=new activexobject ("microsoft.xmlhttp");
      } catch (e) {}
    }
  }
  //Return the created ajax object
  return httprequest;
}

3. Create request and return data display

//Asynchronously request the server to obtain search results
function search () {
  if (searchreq.readystate == 4 || searchreq.readystate == 0) {
    //Get the value in the text box
    var valstr=escape (document.getelementbyid ("txtsearch"). value);
    //establish connection
    searchreq.open ("get", encodeuri ("search.ashx?search =" + valstr + "&fresh =" + math.random ()), true);
    //Call the handlesearch method when the request status changes
    searchreq.onreadystatechange=handlesearch;
    searchreq.send (null);
  }
}
//Return result processing method
function handlesearch () {
  if (searchreq.readystate == 4) {
    //Element div to get search hint results
    var searchdiv=document.getelementbyid ("search_div");
    searchdiv.innerhtml="";
    //Split the returned text data into an array with ^
    var resultstrarr=searchreq.responsetext.split ("^");
    //loop to build html code
    for (var i=0;i<resultstrarr.length-1;i ++) {
      var htmlstr="<div onmouseover =" selectoverdiv (this, "+ i +");"";
      htmlstr +="onmouseout =" selectoutdiv (this, "+ i +");"";
      htmlstr +="onclick =" setsearch (this.innerhtml);"";
      htmlstr +="class =" search_link ">" + resultstrarr [i] + "</div>";
      searchdiv.innerhtml +=htmlstr;
    }
    showdiv ();
    x=-1;
  }
}

4. Select the data in the data display text box

In the above code, when building the html code in a loop, we added three events to the constructed div:

1 onmouseover="selectoverdiv (this," + i + ");"

When the mouse is over, call the selectoverdiv function to pass itself in

2 onmouseout="selectoutdiv (this," + i + ");"

When the mouse is over, call the selectoutdiv function to pass in

3 onclick="setsearch (this.innerhtml);"

When the mouse clicks on the div, the setsearch function is called to pass in the content of the div itself

Then look at the implementation of these methods:

function selectoverdiv (div_value, i) {
  div_value.classname="search_link_over";
  var my_div=document.getelementbyid ("search_div"). getelementsbytagname ("div")
  var the_num=my_div.length;
  for (var k=0;k<the_num;k ++) {
    selectout (my_div [k]);
    if (k == i) {
      selectover (my_div [k])
    }
  }
  ischeckdiv=true;
  x=i;
}
function selectoutdiv (div_value, i) {
  ischeckdiv=false;
  div_value.classname="search_link";
  x=i;
}
function setsearch (value) {
  //The event of emptying the content of the text box is because when we copy the selected value, the event will be triggered
  //So empty the event first
  clearos ();
  document.getelementbyid ("txtsearch"). value=value;
  //Set this property to false. The hidden div will be hidden when calling the hiddendiv function.
  ischeckdiv=false;
  hiddendiv ();
  //Add the modification time again after the assignment is completed
  getos ();
}
function showdiv () {
  var content=document.getelementbyid ("txtsearch"). value;
  var divconten=document.getelementbyid ("search_div"). innerhtml;
  if (content!="" && divconten!="") {
    document.getelementbyid ("search_div"). style.display="block"
  } else {
  ischeckdiv=false;
  hiddendiv ();
  }
}
function hiddendiv () {
  if (ischeckdiv == false) {
    document.getelementbyid ("search_div"). style.display="none";
    document.getelementbyid ("search_div"). innerhtml="";
  }
}

5.Add keyboard up and down keys to select prompt data and enter key to select data to text box

var index=-1;//Indicates the currently selected row index
function keydown () {
  var value=event.keycode
  //Up 38, Down 40, Enter 13
  var the_key=event.keycode
  //Judge whether the prompt div is in a real state
  if (document.getelementbyid ("search_div"). style.display!="none") {
    //Get the rows used inside
    var my_div=document.getelementbyid ("search_div"). getelementsbytagname ("div")
    var the_num=my_div.length;
    switch (the_key) {
      case 40://down
        //Determine whether the index has reached the bottom
        if (index == the_num-1) {
          index=0;
        } else {
          index ++;
        }
        //clear all selected
        for (var i=0;i<the_num;i ++) {
          selectout (my_div [i]);
        }
        //Select the corresponding index line according to index
        for (i=0;i<the_num;i ++) {
          if (i == index) {
            selectover (my_div [i])
          }
        }
        break;
      case 38://up
        //Determine whether the index has reached the top
        if (index == 0) {
          index=the_num-1;
        } else {index--;}
        //clear all selected
        for (var i=0;i<the_num;i ++) {
          selectout (my_div [i]);
        }
        //Select the corresponding index line according to index
        for (i=0;i<the_num;i ++) {
          if (i == index) {
            selectover (my_div [i])
          }
        }
        break;
      case 13://Enter
        //Put selected content into text box
        if (my_div [index] .innerhtml!=null) {
          setsearch (my_div [index] .innerhtml);
        }
        break;
    }
  }
}
document.onkeydown=keydown;
</pre>
</div>
<p>
3. Server-side design
</p>
<p>
(1) Implement a virtual data source
</p>
<p>
The keywords came from the front desk.
There must be data matching in the background,For the sake of simplicity, I will not create a database.
</p>
<p>
Steps:Right-click on the project->Add New Item->Select the general handler named:search.ashx Write the code as follows:
</p>
<div>
<pre>
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.data;
using system.data.sqlclient;
using system.text;
using system.codedom;
using system.globalization;
using system.componentmodel;
using system.collections;
public class search:ihttphandler {
  //define a data source
  public list<string>datasource
  {
    get
    {
      list<string>list=new list<string>()
      {
        "I love c#",        "I love .net",        "I love Microsoft technology"
      };
      return list;
    }
  }
  public void processrequest (httpcontext context) {
    context.response.contenttype="text/plain";
  }
  public bool isreusable {
    get {
      return false;
    }
  }
}

(2) Search the data source and return the fixed format data as a string

Then we need to add our search data source to the processreques method to build the corresponding data set,The stitching result string is returned to the client.code show as below:

public void processrequest (httpcontext context) {
    context.response.contenttype="text/plain";
    //Accept client keywords and decode
   string searchstr=httputility.urldecode (context.request.querystring ["search"]. tostring (), system.text.encoding.utf8);
    //Search for matching keywords in the data source collection
    var result=(from string n in datasource
             where n.contains (searchstr)
             select n) .tolist<string>();
    stringbuilder sb=new stringbuilder (100);
    //Split matching keywords into a string with the symbol ^
    foreach (string str in result as list<string>)
    {
      sb.appendformat ("{0} ^", str);
    }
    //Return to the client
    context.response.write (sb.tostring ());
  }

Then our ajax-based search prompt function is successfully completed,The effect is as follows:

  • Previous Example analysis of custom tag usage in jsp
  • Next Java implementation of asynchronous call example code