/**////
/// 生成带CDATA的节点
/// ///
XmlDocument
///
元素名称
///
CDATA值
///
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;//返回
}
catch (Exception ex)
{
throw ex;
}
}
Helper#region Helper
/**////
/// 向页面输出xml内容
/// ///
xml内容
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();
}
/**////
/// 创建Ajax返回信息
/// ///
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();
}
/****////
/// 向页面输出xml内容
/// ///
xml内容
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 many topics about Ajax on the Internet, but many of them are implemented using control open source frameworks. In particular, vs2008 integrates many ajax controls, which tightly encapsulates the ajax execution process. I have also used these frameworks and controls, and they feel great. But recently, on a whim, I wanted to see how ajax is executed, so I wanted to implement it myself, which just happened to exercise my js skills. Without further ado, as the title states, let’s take a look at the execution process.
1. This implementation uses a total of two pages: AjaxTest6.aspx and Ajax.aspx
Among them, AjaxTest6.aspx is the page that initiates the request, and Ajax.aspx gets the request of AjaxTest6.aspx and processes it. .
Processing process: (1) AjaxTest6.aspx initiates an http request ---> (2) Ajax.aspx obtains the parameters in the url, performs query operations in the database based on these parameters and returns the results (data set) -- ->(3) Process the returned data set as XML and output it through response. Note that the format of the output data now is xml --- (4) AjaxTest6.aspx obtains the output xml data of Ajax.aspx and displays it
2. The js code in AjaxTest6.aspx
< script language="javascript" type="text/javascript"> script>
< script language="javascript" type="text/javascript"> script>
Description: The first function createXMLHttpRequest is used to create an XMLHttpRequest object. For detailed descriptions of this object, please refer to related articles. Now you just need to understand that this object is used when we use http requests to send data and use xml to transfer data. , after the declaration, we can use it below
The second function is used to send http requests. Generally, the URL has parameters, through xmlhttp.open("GET","Tools/Ajax.aspx? cateid=" vr1,true); We can see from this sentence that a request with parameters is sent to Ajax.aspx. Ajax.aspx captures this parameter and then executes a query in the database based on this parameter. The specific processing process will be described in detail below. .
In this function we also need to pay attention to the sentence view plaincopy to clipboardprint?
xmlhttp.onreadystatechange=handleStateChange;//This method is called when the request status changes
xmlhttp.onreadystatechange=handleStateChange;//In This method is called 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 means initialization, 1 means loading, 2 means loaded. , 3 means interactive, 4 means completed
So the above code means that the handleStateChange method will be executed as long as the state of the xmlhttp object changes. Its specific functions are as follows:
This method first finds the div that displays the data. tag (ret), and then determine the execution status of xmlhttp. When the status value becomes 4 and xmlhttp.status==200 (status is the server's http status code 200 corresponding to OK and 404 corresponding to Not Found. If you are not very familiar with the xmlhttprequest object, It is recommended that you familiarize yourself with it first)
Obviously when xmlhttp.onready==4 and xmlhttp.stauts==200 means that all the data has been read out on the server side. At this time, the data is placed in an xml file. This xml file We generate it on the server side.
Everything is ready for program execution. Now we just need to read the xml file from the browser. At this time, you should pay attention to the last function GetText() we will talk about below.
This function first tells the browser that we want to read an xml object (of course you can also set it to a string format, for example: var xmlDoc =xmlhttp.responseText); The reason why we set the data set to xml format is because it can be parsed into a DOM object at this time, so that we can process it very flexibly below.
Now that we have finished talking about the client code, let’s talk about the server-side execution process. This process is completed in the post-code of Ajax.aspx
1. First, we get the url in the Page_Load event parameter, which is sent from AjaxTest6.aspx. Then execute the query based on this parameter. I will not explain the specific code in detail. You can understand it at a glance. 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: As can be seen from GetTitle (int id), I converted the data read from the library into a string and handed it to the CreateResponse method (it may not be appropriate here because it may not be safe when the amount of data is large) , the following is about the operation of converting data into xml files