Javascript + XMLHttpRequest + asp.net does not need to read database data.
The Code is as follows:
/**////
/// Generate a node with CDATA
///
/// XmlDocument
/// Element name
/// CDATA Value
/// XmlElement
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
/**////
/// Create Ajax return information
///
///
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 ();
}
/**////
/// Output xml content to the page
///
/// Xml content
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 ();
}
/**////
/// Generate a node with CDATA
///
/// XmlDocument
/// Element name
/// CDATA Value
/// XmlElement
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
/**////
/// Create Ajax return information
///
///
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 ();
}
/**////
/// Output xml content to the page
///
/// Xml content
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.aspx
The Code is as follows:
<Script language = "javascript" type = "text/javascript">
<Script language = "javascript" type = "text/javascript">
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 p 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:
The 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.