Common Automatic completion functions-Ajax + asp.net

Source: Internet
Author: User
After learning ajax for a while, we should also make some practical things out. Some websites have many professional terms, you need to provide the same page function as the dictionary for the viewer to use so that you can refer to the meaning of the term at any time.
The so-called functions like a dictionary must have the search function. How can we design the search function to make it easier for users to use this dictionary? I believe that you have also used Kingsoft Powerword. When you use a Powerword to search for words, you only need to enter a letter and the words below will be similar, which will gradually narrow down the scope of your search, in this way, when you are not clear about the spelling of a word, you can enter a part and find the corresponding word below for quick search.
Next I will imitate this function to make a simple dictionary search function, that is, the function is automatically completed. Needless to say, it's still the old method. It's even clearer to paste a few images first.
1. When we need to search for a word, enter a letter in the search input box. As we enter a word, the corresponding prompt appears in the input box, for example:

When I enter the letter B, all items in all databases that start with the letter B are displayed. This is real-time, and other letters can be entered, then the search scope is gradually reduced. For example

:) You can click a project below to automatically fill it in the text box.
2. The principles are clear. I will post the main program below for you to see. The program consists of C # background code and javascript code.
A) C # background code:
Create a new page named DictionaryAutoComplete. aspx. delete all the other code on the page except the declaration part of the first line, and then go to the C # code generation in the background. (The using System. Text; and using System. Data. SqlClient namespaces must also be referenced on the page)
Private void GetXmlData ()
{// This is used to obtain the project data prompted in the drop-down list box. The obtained data is output in XML format.
SqlConnection conn = new SqlConnection ("server =.; database = test; uid = sa; pwd = ;");
String names = Request. QueryString ["names"];
StringBuilder xmlData = new StringBuilder ();
XmlData. AppendLine (@ "<? Xml version = '1. 0' encoding = 'utf-8'?> ");
XmlData. AppendLine (@ "<response> ");
String SQL = "";
SqlCommand cmd = new SqlCommand ();
SQL = "select * from Dictionary where words like '" + names + "% '";
Cmd = new SqlCommand (SQL, conn );
Conn. Open ();
SqlDataReader sdr = cmd. ExecuteReader ();
While (sdr. Read ())
{
XmlData. AppendLine (@ "<res>" + sdr ["words"]. ToString () + "</res> ");
}
Sdr. Close ();
Conn. Close ();
XmlData. AppendLine (@ "</response> ");
Response. Write (xmlData. ToString ());
}

In Page_Load on this page, enter:
Response. Clear ();
Response. ContentType = "text/xml"; // set the output format to XML.
Response. Charset = "UTF-8"; // set the output encoding to UTF-8
This. GetXmlData ();

B) javascript code:
Create a js file and enter the following code
// JScript File
// Dictionaryajax. js

Var XMLHttpReq;
Var completeDiv;
Var inputField;
Var completeTable;
Var completeBody;
// Create an XMLHttpRequest object
Function createXMLHttpRequest (){
If (window. XMLHttpRequest) {// Mozilla Browser
XMLHttpReq = new XMLHttpRequest ();
}
Else if (window. ActiveXObject) {// IE browser
Try {
XMLHttpReq = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
XMLHttpReq = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){}
}
}
}

// Send the matching request Function
Function findNames (){
InputField = document. getElementById ("names ");
CompleteTable = document. getElementById ("complete_table ");
CompleteDiv = document. getElementById ("popup ");
CompleteBody = document. getElementById ("complete_body ");
If (inputField. value. length> 0 ){
CreateXMLHttpRequest ();
Var url = "DictionaryAutoComplete. aspx? Names = "+ escape (inputField. value );//
XMLHttpReq. open ("GET", url, true );
XMLHttpReq. onreadystatechange = processMatchResponse; // specify the response function.
XMLHttpReq. send (null); // send the request
} Else {
ClearNames ();
}
}

// Function for processing the returned matching information
Function processMatchResponse (){
If (XMLHttpReq. readyState = 4) {// judge the object status
If (XMLHttpReq. status = 200) {// The information has been returned successfully. Start to process the information.
SetNames (XMLHttpReq. responseXML. getElementsByTagName ("res "));
} Else {// The page is abnormal.
Window. alert ("the page you requested has an exception. ");
}
}
}

// Generate matching rows with the input content
Function setNames (names ){
ClearNames ();
Var size = names. length;
SetOffsets ();
Var row, cell, txtNode;
For (var I = 0; I <size; I ++ ){
Var nextNode = names [I]. firstChild. data;
Row = document. createElement ("tr ");
Cell = document. createElement ("td ");
Cell. onmouseout = function (){
This. className = 'mouseover ';
};
Cell. onmouseover = function (){
This. className = 'mouseout ';
};
Cell. setAttribute ("bgcolor", "# ffddcc ");
Cell. setAttribute ("border", "0 ");
Cell. onclick = function (){
CompleteField (this );
};
TxtNode = document. createTextNode (nextNode );
Cell. appendChild (txtNode );
Row. appendChild (cell );
CompleteBody. appendChild (row );
}
}

// Set the display position
Function setOffsets (){
CompleteTable. style. width = "auto"; // The automatically completed prompt box is displayed. The width is automatically expanded or reduced.
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 ";
}

// Calculate the display position
Function calculateOffset (field, attr ){
Var offset = 0;
While (field ){
Offset + = field [attr];
Field = field. offsetParent;
}
Return offset;
}

// Input box
Function completeField (cell ){
InputField. value = cell. firstChild. nodeValue;
ClearNames ();
}

// Clear the Automatic completion line
Function clearNames (){
Var ind = completeBody. childNodes. length;
For (var I = ind-1; I> = 0; I --){
CompleteBody. removeChild (completeBody. childNodes [I]);
}
CompleteDiv. style. border = "none ";
}

Create a new Dictionary. aspx page, which contains a TextBox Control, name it dictionarypolicnames, and import the js file to the page. Then all the functions are completed. Try it now ~~~~ The HTML code is as follows:

<H1>
Dictionary <P>
<Label for = "names">
Search:
<Asp: TextBox ID = "names" runat = "server"> </asp: TextBox> </label>
<Asp: Button ID = "Button1" runat = "server" Text = "Go"/>
</P>
<Div style = "position: absolute;" id = "popup" runat = "server">
<Table id = "complete_table" border = "0" cellspacing = "0" cellpadding = "0" style = "background-color: # cceeff;">
<Tbody id = "complete_body">
</Tbody>
</Table>
</Div>

Do not forget to add the following code to the. cs file Page_load:

This. names. Attribute. Add ("onKeyup", "findNames ();");

PS: Some of my friends have problems with the tests. It is my negligence. Thank you for your correction. In addition, I have sent all the copied files that need to be debugged to you. Please check them.

This example: Click to download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.