Javascript + XMLHttpRequest + asp.net does not need to read database data.

Source: Internet
Author: User

Copy codeThe Code is as follows:/** // <summary>
/// Generate a node with CDATA
/// </Summary>
/// <Param name = "xDocument"> XmlDocument </param>
/// <Param name = "elementName"> element name </param>
/// <Param name = "cdataValue"> CDATA value </param>
/// <Returns> XmlElement </returns>
Public static XmlElement CreateXmlNodeCDATA (XmlDocument xDocument, string elementName, string cdataValue)
{
Try
{
XmlElement xElement = xDocument. CreateElement (elementName );
XmlCDataSection cdata = xDocument. CreateCDataSection (cdataValue );
XElement. AppendChild (cdata );
Return xElement; // return
}
Catch (Exception ex)
{
Throw ex;
}
}
Helper # region Helper
/** // <Summary>
/// Create Ajax return information
/// </Summary>
/// <Param name = "result"> </param>
Private void CreateResponse (string result)
{
XmlDocument xDocument = new XmlDocument ();
XmlDeclaration declare = xDocument. CreateXmlDeclaration ("1.0", "UTF-8", "yes ");
XmlElement root = xDocument. CreateElement ("root ");
XmlElement eleResponse = CreateXmlNodeCDATA (xDocument, "response", result );
Root. AppendChild (eleResponse );
XDocument. AppendChild (declare );
XDocument. AppendChild (root );
ResponseXML (xDocument );
System. Web. HttpContext. Current. Response. End ();
}
/** // <Summary>
/// Output xml content to the page
/// </Summary>
/// <Param name = "xmlnode"> xml content </param>
Private void ResponseXML (XmlDocument xmlNode)
{
System. Web. HttpContext. Current. Response. Expires = 0;
System. Web. HttpContext. Current. Response. Clear ();
System. Web. HttpContext. Current. Response. Cache. SetNoStore ();
System. Web. HttpContext. Current. Response. ContentType = "text/xml ";
System. Web. HttpContext. Current. Response. Write (xmlNode. OuterXml );
System. Web. HttpContext. Current. Response. End ();
}
/** // <Summary>
/// Generate a node with CDATA
/// </Summary>
/// <Param name = "xDocument"> XmlDocument </param>
/// <Param name = "elementName"> element name </param>
/// <Param name = "cdataValue"> CDATA value </param>
/// <Returns> XmlElement </returns>
Public static XmlElement CreateXmlNodeCDATA (XmlDocument xDocument, string elementName, string cdataValue)
{
Try
{
XmlElement xElement = xDocument. CreateElement (elementName );
XmlCDataSection cdata = xDocument. CreateCDataSection (cdataValue );
XElement. AppendChild (cdata );
Return xElement; // return
}
Catch (Exception ex)
{
Throw ex;
}
}
Helper # region Helper
/** // <Summary>
/// Create Ajax return information
/// </Summary>
/// <Param name = "result"> </param>
Private void CreateResponse (string result)
{
XmlDocument xDocument = new XmlDocument ();
XmlDeclaration declare = xDocument. CreateXmlDeclaration ("1.0", "UTF-8", "yes ");
XmlElement root = xDocument. CreateElement ("root ");
XmlElement eleResponse = CreateXmlNodeCDATA (xDocument, "response", result );
Root. AppendChild (eleResponse );
XDocument. AppendChild (declare );
XDocument. AppendChild (root );
ResponseXML (xDocument );
System. Web. HttpContext. Current. Response. End ();
}
/** // <Summary>
/// Output xml content to the page
/// </Summary>
/// <Param name = "xmlnode"> xml content </param>
Private void ResponseXML (XmlDocument xmlNode)
{
System. Web. HttpContext. Current. Response. Expires = 0;
System. Web. HttpContext. Current. Response. Clear ();
System. Web. HttpContext. Current. Response. Cache. SetNoStore ();
System. Web. HttpContext. Current. Response. ContentType = "text/xml ";
System. Web. HttpContext. Current. Response. Write (xmlNode. OuterXml );
System. Web. HttpContext. Current. Response. End ();
}

There are already many topics about Ajax on the Internet, but many of them are implemented using the open-source control framework. In particular, vs2008 integrates a lot of ajax controls to strictly encapsulate the ajax execution process. I have also used these frameworks and controls, and it feels great. However, recently, I was excited and wanted to see how ajax was executed. I just wanted to implement it myself and exercise my JavaScript skills. Let's take a look at the execution process.
1. Two pages are used in this implementation: AjaxTest6.aspx and Ajax. aspx.
Here, AjaxTest6.aspx is the page that initiates the request. Ajax. aspx gets the AjaxTest6.aspx request and processes the page.
Processing process: (1) AjaxTest6.aspx initiates an http request ---> (2) Ajax. aspx obtains the parameters in the url, performs the query operation in the Database Based on this parameter, and returns the result (Dataset) ---> (3) to process the returned dataset in xml and output it through response. Note that the current output data format is xml --- (4) AjaxTest6.aspx to get Ajax. aspx to output xml data and display
2. js code in AjaxTest6.aspxCopy codeThe Code is as follows: <script language = "javascript" type = "text/javascript"> <! --
Var xmlhttp;
Function createXMLHttpRequest () // create an instance for xmlhttp
{
If (window. ActiveXObject)
Xmlhttp = new ActiveXObject ('Microsoft. xmlhttp ');
Else if (window. XMLHttpRequest)
{
Xmlhttp = new XMLHttpRequest ();
}
}
Function stateRequest (vr1) // Status Request
{
// Alert ('it seems that stateRequest has been executed ');
CreateXMLHttpRequest (); // reference the xmlhttp instance
Xmlhttp. onreadystatechange = handleStateChange; // call this method when the Request status changes
Xmlhttp. open ("GET", "Tools/Ajax. aspx? Cateid = "+ vr1, true );
Xmlhttp. send (null );
}
Function handleStateChange ()
{
// Alert ("it seems that handleStateChange () has been executed ");
Var divRet = document. getElementById ("ret ");
If (xmlhttp. readyState = 4)
{
If (xmlhttp. status = 200)
{
Var text = GetText ();
DivRet. innerHTML = text;
}
}
Else
DivRet. innerHTML = " <B> loading data </ b> ";
}
Function GetText ()
{
Var xmlDoc = xmlhttp. responseXML;
// Alert (xmlDoc. toString ());
If (xmlDoc = null)
{
// Alert ("has it been executed here ");
Return "no data! ";
}
Var requestNode = xmlDoc. getElementsByTagName ("response") [0];
Var node = requestNode. firstChild. nodeValue;
// Alert (node );
Return node
}
// --> </Script>
<Script language = "javascript" type = "text/javascript"> <! --
Var xmlhttp;
Function createXMLHttpRequest () // create an instance for xmlhttp
{
If (window. ActiveXObject)
Xmlhttp = new ActiveXObject ('Microsoft. xmlhttp ');
Else if (window. XMLHttpRequest)
{
Xmlhttp = new XMLHttpRequest ();
}
}
Function stateRequest (vr1) // Status Request
{
// Alert ('it seems that stateRequest has been executed ');
CreateXMLHttpRequest (); // reference the xmlhttp instance
Xmlhttp. onreadystatechange = handleStateChange; // call this method when the Request status changes
Xmlhttp. open ("GET", "Tools/Ajax. aspx? Cateid = "+ vr1, true );
Xmlhttp. send (null );
}
Function handleStateChange ()
{
// Alert ("it seems that handleStateChange () has been executed ");
Var divRet = document. getElementById ("ret ");
If (xmlhttp. readyState = 4)
{
If (xmlhttp. status = 200)
{
Var text = GetText ();
DivRet. innerHTML = text;
}
}
Else
DivRet. innerHTML = " <B> loading data </ b> ";
}
Function GetText ()
{
Var xmlDoc = xmlhttp. responseXML;
// Alert (xmlDoc. toString ());
If (xmlDoc = null)
{
// Alert ("has it been executed here ");
Return "no data! ";
}
Var requestNode = xmlDoc. getElementsByTagName ("response") [0];
Var node = requestNode. firstChild. nodeValue;
// Alert (node );
Return node
}
// --> </Script>

Note: The first function createXMLHttpRequest is used to create an XMLHttpRequest object. For details about this object, refer to relevant articles. Now we only need to understand that when we use http requests to send data, this object is used when xml is used to transmit data. After the object is declared, we can use it below.
The second function is used to send an http request. Generally, the url carries parameters through xmlhttp. open ("GET", "Tools/Ajax. aspx? Cateid = "+ vr1, true); we can see that it is directed to Ajax. aspx sends a request with parameters, Ajax. aspx captures this parameter and then executes queries in the Database Based on this parameter. The specific process is described below.
In this function, we also need to pay attention to one sentence: view plaincopy to clipboardprint?
Xmlhttp. onreadystatechange = handleStateChange; // call this method when the Request status changes
Xmlhttp. onreadystatechange = handleStateChange; // call this method when the Request status changes
Because the xmlhttp object is divided into several stages during execution, each stage corresponds to a different status value: 0 indicates initialization, 1 indicates loading, 2 indicates loading, 3 indicates interaction, 4 indicates completion
Therefore, the code above indicates that the handleStateChange method is executed as long as the status of the xmlhttp object changes. Its specific functions are as follows:
This method first finds the div tag (ret) that shows the data, and then judges the execution status of xmlhttp. When the status value changes to 4 and xmlhttp. status = 200 (status indicates that the http status Code 200 of the server corresponds to OK 404 and Not Found. If you are Not familiar with xmlhttprequest objects, you are advised to familiarize yourself first)
Obviously, when xmlhttp. onready = 4 and xmlhttp. stauts = 200 indicates that all data has been read from the server. At this time, the data is stored in an xml file, which is generated on the server.
The program is ready for execution now, and now only the xml file cannot be read from the browser. Note that the last function GetText ()
This function first tells the browser that we want to read an xml Object (of course, you can also set it to string format, for example: var xmlDoc = xmlhttp. responseText); the reason why we set the dataset to xml format is that it can be parsed as a DOM object, so we can handle it quite flexibly.
Now we have finished the client code. The Execution Process on the server is completed in the post code of Ajax. aspx.
1. First, we get the url parameter in the Page_Load event, which is sent from AjaxTest6.aspx. Then execute the query based on this parameter. I will not explain the specific code in detail. You will understand it at a Glance. The Code is as follows:Copy codeThe Code is as follows: private static readonly string SQL = "server = xxx; database = xxx; uid = sa; pwd = xxx ";
Protected void Page_Load (object sender, EventArgs e)
{
String id = Request. QueryString ["cateid"];
System. Threading. Thread. Sleep (2000 );
GetTitle (Convert. ToInt32 (id ));
}

Private DataTable GetLogs (int cateid)
{
Using (SqlConnection con = new SqlConnection (SQL ))
{
Con. Open ();
String select = "SELECT Id, CateId, LogTitle FROM Logs WHERE CateId =" + cateid;
SqlDataAdapter sda = new SqlDataAdapter (select, con );
DataTable dt = new DataTable ();
Sda. Fill (dt );
Con. Close ();
Return dt;
}
}

Public void GetTitle (int id)
{
DataTable dt = GetLogs (id );
StringBuilder sb = new StringBuilder ();
If (dt! = Null & dt. Rows. Count> 0)
{
For (int I = 0; I <dt. Rows. Count; I ++)
{
Sb. AppendLine (dt. Rows [I] [2]. ToString ());
}
CreateResponse (sb. ToString ());
}
}
Private static readonly string SQL = "server = xxx; database = xxx; uid = sa; pwd = xxx ";
2 protected void Page_Load (object sender, EventArgs e)
3 {
4 string id = Request. QueryString ["cateid"];
5 System. Threading. Thread. Sleep (2000 );
6 GetTitle (Convert. ToInt32 (id ));
7}
8
9 private DataTable GetLogs (int cateid)
{
Using (SqlConnection con = new SqlConnection (SQL ))
{
Con. Open ();
String select = "SELECT Id, CateId, LogTitle FROM Logs WHERE CateId =" + cateid;
SqlDataAdapter sda = new SqlDataAdapter (select, con );
DataTable dt = new DataTable ();
Sda. Fill (dt );
Con. Close ();
Return dt;
}
}

Public void GetTitle (int id)
{
DataTable dt = GetLogs (id );
StringBuilder sb = new StringBuilder ();
If (dt! = Null & dt. Rows. Count> 0)
{
For (int I = 0; I <dt. Rows. Count; I ++)
{
Sb. AppendLine (dt. Rows [I] [2]. ToString ());
}
CreateResponse (sb. ToString ());
}
}

Note: Through GetTitle (int id), we can see that the data I read from the database is converted to a string and handed over to the CreateResponse method (this method may not be suitable because it may not be safe when the data volume is large ), the following describes how to convert data into xml files.

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.