In peacetime software development, the search for information is often encountered, to increase the search keyword hint is a good way to improve the user experience. Today on the ASP.net how to use Ajax to achieve the search information tips!
1. Some knowledge points that need to be understood
(1) The creation of different browsers for Ajax objects
The implementations of Ajax (XMLHttpRequest) objects are different for browsers, ie browsers implement AJAX objects through ActiveX controls. Other browsers such as Firefox, which implements Ajax objects as objects within a browser, are called XMLHttpRequest, so different browsers create Ajax objects differently, so let's look at how Ajax objects are created between different browsers:
Create under IE browser:
IE browser
try {
//ie5.0
HttpRequest = new ActiveXObject ("Msxml2.xmlhttp");
} catch (e) {
try {
/ /ie5.5 above version
HttpRequest = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (e) {}
create at the following Firefox browser:
Firefox, Safari and other browsers
HttpRequest = new XMLHttpRequest ();
Multi-Browser Ajax object creation function:
function Createajaxobj () {
var HttpRequest = false;
To determine whether or not to include the XMLHttpRequest object PS: Future IE high may also inherit the secondary object
if (window). XMLHttpRequest) {
//Firefox, Safari and other browsers
HttpRequest = new XMLHttpRequest ();
if (httprequest.overridemimetype)
httprequest.overridemimetype (' text/xml ');
} Determines whether the active control object
else if (window) is supported. ActiveXObject) {
//ie browser
try {
//ie5.0
HttpRequest = new ActiveXObject ("Msxml2.xmlhttp");
} catch (E) {
try {
//ie5.5
HttpRequest = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (e) {}< c19/>}
//Returns the created Ajax object return
HttpRequest;
}
(2) text box content changes in the use of events under different browsers
The event that the content of the text box changes does not currently have a standard version. We currently only care about IE and Firefox good, then in IE and Firefox under the two time separately how to say?
Ie:onpropertychange
Firefox:oninput
So how do you attach a change event to a text box according to the browser when the page loads?
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 Browser type
if (navigator.userAgent.indexOf ("MSIE") > 0) {
//At this point assume that the text box ID is ' Txtsearch '
//For the text box to append IE supported event
document.getElementById (' Txtsearch '). attachevent ("Onpropertychange", search);
Ostyep = "MSIE";
} else if (navigator.userAgent.indexOf ("Firefox") > 0) {
//At this point assume that the text box ID is ' txtsearch '
/For the text box to append the events
supported by Firefox document.getElementById (' Txtsearch '). AddEventListener ("Input", search, false);
Ostyep = "Firefox";
}
3. Clear the corresponding event to the text box according to the browser version
function ClearOS () {
if (Navigator.userAgent.indexOf ("MSIE") > 0) {
Now assume the text box ID is ' Txtsearch '
Clear the events supported by IE for text boxes
document.getElementById (' Txtsearch '). DetachEvent ("Onpropertychange", search);
Ostyep = "MSIE";
else if (navigator.userAgent.indexOf ("Firefox") > 0) {
Now assume the text box ID is ' Txtsearch '
Clear the events supported by Firefox for text boxes
document.getElementById (' Txtsearch '). RemoveEventListener ("Input", search, false);
Ostyep = "Firefox";
}
}
Second, the design of the client
(1) Implementation of the process analysis
After you know the above points, let's take a look at the whole process of implementing the search hints:
1 First, the client through the text box input event capture input keyword
2 submitted to the server via our previously created Ajax object.
3 The server accepts the submitted keyword and makes a query to return the result set to the client for display
The process is as follows:
(2) The writing of the style
Then let's take a look at the style, which includes the text box when the mouse moved up to the border color and search results row selected style, and so on, here is not in detail, listed for reference:
<style type= "Text/css" media= "screens" > 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 on the prompt list when the mouse is moved/* search_link_over {background-color: #E8F2FE;
Cursor:pointer;
line-height:24px;
text-indent:6px;
/* Set the style sheet to display the search hint 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 Ya Hei", "Song Body", Candara;
Font-weight:normal;
Color: #666;
Margin:auto;
Border:none;
text-indent:8px;
/* Mouse put the 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 left text box style/* Maininputfocus {width:552px;
height:30px;
border:1px solid #41b5f2;
/* Click on the 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) aspx page and ajax_search.js file writing
The next step is a more important one, where the ASPX page and the Ajax_search.js file contain a whole range of methods for displaying and requesting, for example:
1. The implementation of the page
<body onload= "Getos ()" onkeydown= "if (event.keycode==13) return false;" >
<form id= "Form1" runat= "Server" >
<div>
<div class= "Myborder" onmouseover= " This.classname= ' Maininputover ' "onmouseout=" this.classname= ' Myborder ' "onclick=" this.classname= ' MainInputFocus ' " >
<input type= "text" id= "Txtsearch" name= "Txtsearch" onblur= "Hiddendiv ()" alt= "Searchcriteria" Autocomplete= "Off" class= "Maininput"/>
</div>
<!--the DIV as the result of a realistic search hint--> <div id=
" Search_div "style=" margin-top:0px "></div>
</div>
</form>
</body>
2. Create Ajax objects from browsers
var searchreq = Createajaxobj ();
var ostyep = '; function Getos () {//Judge 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 ("in
Put ", search, false);
Ostyep = "Firefox"; The function ClearOS () {if (Navigator.userAgent.indexOf ("MSIE") > 0) {document.getElementById (' txtsearch '). Det
Achevent ("Onpropertychange", search);
Ostyep = "MSIE"; else if (navigator.userAgent.indexOf ("Firefox") > 0) {document.getElementById (' Txtsearch '). RemoveEventListener (
"Input", search, false);
Ostyep = "Firefox";
The function createajaxobj () {var HttpRequest = false; To determine whether or not to include the XMLHttpRequest object PS: Future IE high may also inherit the secondary 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 else if (window) is supported.
ActiveXObject) {//ie browser try {//ie5.0 HttpRequest = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {try {//ie5.5 above HttpRequest = new ActiveXObject ("Microsoft.XMLHTTP");
The catch (e) {}}}//Returns the created Ajax object return HttpRequest;
}
3. Create the display of request and return data
Asynchronous request server Fetch search results function search () {if (searchreq.readystate = 4 | | searchreq.readystate = 0) {//Get the value in the text box V
Ar 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 state changes searchreq.onreadystatechange = Handlesearch;
Searchreq.send (NULL); }//Return result processing method function Handlesearch () {if (searchreq.readystate = 4) {//the element div var searchdiv that gets the result of the search hint = docu
Ment.getelementbyid ("Search_div");
searchdiv.innerhtml = "";
Use ^ to divide the returned text data into groups var Resultstrarr = searchReq.responseText.split ("^"); Loop build HTML code for (var i = 0; i < resultstrarr.length-1 i++) {var htmlstr = ' <div onmouseover= ' Selectov Erdiv (This, ' +i+ ');
'; Htmlstr + = ' onmouseout= ' Selectoutdiv (this, ' +i+ '); "
'; Htmlstr + = ' onclick= ' Setsearch (this.innerhtml); "
'; Htmlstr = ' class= ' Search_link "style=" Display:block;width:100%; "> ' + resultstrarr[i] + ' </div> ';
searchdiv.innerhtml + = Htmlstr;
} showdiv ();
x =-1; }
}
4. Select the data in the Data display text box
In the top code, when looping through the construction of HTML code, we add three events to the constructed Div, respectively:
1 onmouseover= "Selectoverdiv (This, ' +i+ ');"
When the mouse is put up, call the Selectoverdiv function to pass yourself in
2 onmouseout= "Selectoutdiv (This, ' +i+ ');"
When the mouse is put up, call the Selectoutdiv function to pass yourself in
3 onclick= "Setsearch (this.innerhtml);"
When the mouse clicks on the DIV, call the Setsearch function to pass the contents of the Div
So let's 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) {//Empty the contents of the text box the event is changed because the event triggers when we copy the selected value//So clear the event first ClearOS ();
document.getElementById ("Txtsearch"). Value = value;
Set this property to False when the call to the HIDDENDIV function hides the hint result div ischeckdiv = false;
Hiddendiv ();
Additional modification Time Getos () after the assignment is completed;
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 (); The function Hiddendiv () {if (Ischeckdiv = = False) {document.getElementById ("Search_div"). Style.display = None
";
document.getElementById ("Search_div"). InnerHTML = ';
}
}
5. Increase the keyboard up and down key check the prompt data and enter to select the data to the text box
var index =-1; Represents the currently selected row index function KeyDown () {var value = event.keycode//Up 38, down 40, enter var The_key = event.keycode//judgment hint di Whether V is a realistic state if (document.getElementById ("Search_div"). Style.display!= "None") {//Get inside of the line var my_div = document.ge
Telementbyid ("Search_div"). getElementsByTagName ("div") var the_num = my_div.length;
Switch (the_key) {case 40://down//To determine if index has been to 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)); ////According to index Select the corresponding index row for (i = 0; i < The_num i++) {if (i = = index) {selectover (M)
Y_div[i]}} break;
Case 38://Up//To determine whether index has been to 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]); ////According to index Select the corresponding index row for (i = 0; i < The_num i++) {if (i = = index) {selectover (M)
Y_div[i]}} break; Case 13://Enter///Put the selected content in the text box if (my_div[index].innerhtml!= null) {Setsearch (My_div[index].inne
RHTML);
} break;
}} document.onkeydown = KeyDown;
3. Server-Side design
(1) Implementation of a virtual data source
Front of the key word, the background must have data matching, in order to simple I will not set up a database I will simulate a data source well!
Step: Right Key item--> Add New item--> Select Generic handler named: Search.ashx write code as follows:
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
{ c17/>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 data source return fixed format data in string form
And then we're going to add our search data source to the Processreques method. Build returns the corresponding dataset, and the concatenation result string is returned to the client. The code is as follows:
public void ProcessRequest (HttpContext context) {context
. Response.ContentType = "Text/plain";
Accepts client-side keywords and decodes
string searchstr = Httputility.urldecode (context. request.querystring["Search"]. ToString (), System.Text.Encoding.UTF8);
Search data source collection matches the keyword var results
= (from string n in DataSource
where N.contains (searchstr)
select N). Tolist<string> ();
StringBuilder sb = new StringBuilder (m);
Concatenate a matching keyword with a symbol ^ segment into a string
foreach (string str in result as list<string>)
{
sb. AppendFormat ("{0}^", str);
}
Returns the client context
. Response.Write (sb.) ToString ());
}
Then our AJAX based search hint function is completed smoothly, the effect is as follows:
The above is ASP.net use Ajax to implement search tips of the implementation process, the content is very detailed, the idea is very clear, I hope to help you learn.