XMLHttpRequest detailed and operational XML file code

Source: Internet
Author: User
Tags xmlns

XMLHttpRequest detailed and operational XML file code

What is a XMLHttpRequest object?
The XMLHttpRequest object is used to exchange data with the server in the background.

The XMLHttpRequest object is a developer's dream, because you can:

To update a Web page without reloading the page
Request data from the server after the page has been loaded
Receive data from the server after the page has been loaded
Sending data to the server in the background
All modern browsers support the XMLHttpRequest object.

To learn more about XMLHttpRequest objects, learn about our XML DOM tutorial.

Instance: XML HTTP communication with the server when text is typed.
Creating XMLHttpRequest Objects
All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) have built XMLHttpRequest objects.

With a single line of JavaScript code, we can create XMLHttpRequest objects.

Syntax for creating XMLHttpRequest objects:
xmlhttp=new XMLHttpRequest (); Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
xmlhttp= New ActiveXObject ("Microsoft.XMLHTTP"); hint: In the next chapter, we'll retrieve the XML information from the server using the XMLHttpRequest object.
Instance 1
<script type= "text/web Effects"
var xmlhttp;
function loadxmldoc (URL)
{
Xmlhttp=null;
I F (window. XMLHttpRequest)
  {//code for all new browsers
  xmlhttp=new XMLHttpRequest ();
 }
Else if (Window. ActiveXObject)
  {//code for IE5 and IE6
  xmlhttp=new activexobject ("Microsoft.XMLHTTP");
 }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=state_change
  Xmlhttp.open ("Get" , url,true);
  xmlhttp.send (null);
 }
Else
  {
  alert ("Your browser does not support XMLHTTP.");
 }
}

function State_change ()
{
if (xmlhttp.readystate==4)
{//4 = "Loaded"
if (xmlhttp.status==200)
{//= OK
... we code here ...
}
Else
{
Alert ("Problem retrieving XML Data");
}
}
}
</script> Try it for yourself

Note: onReadyStateChange is an event handle. Its value (state_change) is the name of a function that triggers this function when the state of the XMLHttpRequest object changes. The state varies from 0 (uninitialized) to 4 (complete). We execute the code only when the state is 4 o'clock.

Why use Async=true?
Our instance uses "true" in the third parameter of open ().

This parameter stipulates whether the request is processed asynchronously.

True indicates that the script will continue to execute after the Send () method without waiting for a response from the server.

The onReadyStateChange event complicates the code. But this is the safest way to prevent code from stopping without getting a response from the server.

By setting this argument to False, you can omit additional onreadystatechange code. You can use this parameter if the rest of the code does not matter if the request fails.

The XMLHttpRequest object sends a request to the server to send a get way, accesses the server's. ashx file, gets the server response, and triggers the defined callback function.

This article will write a XMLHttpRequest object that asynchronously sends the XML document to the server as a POST request

This article uses environment VS2005 to run VS2005, open an existing project, create a new Web form, and name it postxml.asp tutorial x

The code is as follows:

View Plaincopy to Clipboardprint?


01.&lt;%@ Page language= "C #" autoeventwireup= "true" codefile= "PostXML.aspx.cs" inherits= "_postxml"%&gt;


02.&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt;


03.&lt;html xmlns= "http://www.w3.org/1999/xhtml" &gt;


04.&lt;head runat= "Server" &gt;


&lt;title&gt; Untitled Page &lt;/title&gt;


&lt;script type= "Text/javascript" &gt;&lt;!--


Modified Var xmlhttp=null;


08.


function Createxmlhttprequest ()


10. {


One. if (xmlHttp = null) {


An. if window. XMLHttpRequest) {


//mozilla Browser


XmlHttp = new XMLHttpRequest ();


}else if (window. ActiveXObject) {


//IE Browser


try {


XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");


catch (e) {


try {


XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");


catch (e) {


Alert (' Create failure ');


24.}


25.}


26.}


27.}


28.}


29.


function OpenAjax (XML)


31. {


if (xmlHttp = null)


33. {


Createxmlhttprequest ();


if (xmlHttp = null)


36. {


Alert (' Error ');


return;


39.}


40.}


41.


Xmlhttp.open ("Post", "result.aspx?date=" +new date (). GetTime (), true);


43.


Xmlhttp.onreadystatechange=xmlhttpchange;


45.


Xmlhttp.send (XML);


47.}


48.


function Xmlhttpchange ()


50. {


An. if (xmlhttp.readystate==4)


52. {


if (xmlhttp.status==200)


54. {


document.getElementById (' Resultdiv '). Innerhtml=xmlhttp.responsetext;


56.}


57.}


58.}


59.


function Loadxml (XMLSRC)


61. {


var xmldoc;


The. if (window). ActiveXObject)


64. {


xmldoc = new ActiveXObject (' Microsoft.XMLDOM ');


Xmldoc.async = false;


Xmldoc.load (XMLSRC);


if (xmldoc.parseerror.errorcode!=0)


69. {


Alert ("Error!") "+xmldoc.parseerror.reason);


71.}


72.}


The. else if (document.implementation&amp;&amp;document.implementation.createdocument)


74. {


xmldoc = Document.implementation.createDocument (",", null);


Xmldoc.async=false;


Xmldoc.load (XMLSRC);


78.}


. else


80. {


Bayi. return null;


82.}


83.


XmlDoc return;


85.}


86.


function Postxml (XMLSRC)


88. {


A. var xml;


if (xmlsrc== ')


91. {


Xml= "&lt;?xml version= ' 1.0 ' encoding= ' utf-8 '? &gt;&lt;pet&gt;&lt;type&gt;cats&lt;/type&gt;&lt;type&gt;do Gs&lt;/type&gt;&lt;/pet&gt; ";


93.}


. else


95. {


Xml=loadxml (XMLSRC);


97.}


if (xml==null)


99. {


Alert (' XML document creation failed ');


101.}


102. Else


103. {


OpenAjax (XML);


105.}


106.}


107.


108.//--&gt;&lt;/script&gt;


109.&lt;/head&gt;


110.&lt;body&gt;


&lt;form id= "Form1" runat= "Server" &gt;


112. Send the constructed XML format string &lt;input type= "button" value= "Send" onclick= "Postxml ("); "/&gt;&lt;br/&gt;


113. Send existing XML document &lt;input type= "button" value= "Send" onclick= "postxml (' XMLFile.xml ');"/&gt;


114. &lt;div id= "Resultdiv" &gt;&lt;/div&gt;


&lt;/form&gt;


116.&lt;/body&gt;


117.&lt;/html&gt;


&lt;%@ Page language= "C #" autoeventwireup= "true" codefile= "PostXML.aspx.cs" inherits= "_postxml"%&gt;


&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt;


&lt;html xmlns= "http://www.w3.org/1999/xhtml" &gt;


&lt;head runat= "Server" &gt;


&lt;title&gt; Untitled Page &lt;/title&gt;


&lt;script type= "Text/javascript" &gt;&lt;!--


var xmlhttp=null;





function Createxmlhttprequest ()


{


if (xmlHttp = = null) {


if (window. XMLHttpRequest) {


Mozilla Browser


XmlHttp = new XMLHttpRequest ();


}else if (window. ActiveXObject) {


IE browser


try {


XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");


catch (e) {


try {


XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");


catch (e) {


Alert (' Create failed ');


}


}


}


}


}





function OpenAjax (XML)


{


if (xmlHttp = null)


{


Createxmlhttprequest ();


if (xmlHttp = null)


{


Alert (' Error ');


return;


}


}





Xmlhttp.open ("Post", "result.aspx?date=" +new date (). GetTime (), true);





Xmlhttp.onreadystatechange=xmlhttpchange;





Xmlhttp.send (XML);


}





function Xmlhttpchange ()


{


if (xmlhttp.readystate==4)


{


if (xmlhttp.status==200)


{


document.getElementById (' Resultdiv '). Innerhtml=xmlhttp.responsetext;


}


}


}





function Loadxml (XMLSRC)


{


var xmldoc;


if (window. ActiveXObject)


{


xmldoc = new ActiveXObject (' Microsoft.XMLDOM ');


Xmldoc.async = false;


Xmldoc.load (XMLSRC);


if (xmldoc.parseerror.errorcode!=0)


{


Alert ("Error!") "+xmldoc.parseerror.reason);


}


}


else if (document.implementation&amp;&amp;document.implementation.createdocument)


{


xmldoc = Document.implementation.createDocument (",", null);


Xmldoc.async=false;


Xmldoc.load (XMLSRC);


}


Else


{


return null;


}





return xmldoc;


}





function Postxml (XMLSRC)


{


var xml;


if (xmlsrc== ')


{


Xml= "&lt;?xml version= ' 1.0 ' encoding= ' utf-8 '? &gt;&lt;pet&gt;&lt;type&gt;cats&lt;/type&gt;&lt;type&gt;dogs&lt;/ Type&gt;&lt;/pet&gt; ";


}


Else


{


Xml=loadxml (XMLSRC);


}


if (xml==null)


{


Alert (' XML document creation failed ');


}


Else


{


OpenAjax (XML);


}


}





--&gt;&lt;/script&gt;


&lt;/head&gt;


&lt;body&gt;


&lt;form id= "Form1" runat= "Server" &gt;


Send the constructed XML format string &lt;input type= "button" value= "Send" onclick= "Postxml ("); "/&gt;&lt;br/&gt;


Send an existing XML document &lt;input type= "button" value= "Send" onclick= "postxml (' XMLFile.xml ');"/&gt;


&lt;div id= "Resultdiv" &gt;&lt;/div&gt;


&lt;/form&gt;


&lt;/body&gt;


&lt;/html&gt;

The previous XMLHttpRequest object accesses the server. ashx file (general handler), which is accessed by the. aspx file (another Web form)

Create a new Web form for processing requests named Result.aspx

The code is as follows:

Result.aspx.cs

View Plaincopy to Clipboardprint?


01.using System;


02.using System.Data;


03.using System.Configuration;


04.using System.Collections;


05.using system.web;


06.using System.Web.Security;


07.using System.Web.UI;


08.using System.Web.UI.WebControls;


09.using System.Web.UI.WebControls.WebParts;


10.using System.Web.UI.HtmlControls;


11.using System.Xml;


12.public Partial class Ajax_xmlHttpRequest_Result:System.Web.UI.Page


13.{


protected void Page_Load (object sender, EventArgs e)


15. {


XmlDocument xmldoc = new XmlDocument ();


Xmldoc.load (Request.inputstream);


XmlNodeList selectedpettypes = Xmldoc.getelementsbytagname ("type");


String type = null;


String responsetext = "Selected Pets:";


for (int i = 0; i &lt; Selectedpettypes.count; i++)


22. {


Type = Selectedpettypes[i]. Firstchild.value;


ResponseText = ResponseText + "" + type;


25.}


Response.Write (ResponseText);


Response.End ();


28.}


29.}


Using System;


Using System.Data;


Using System.Configuration;


Using System.Collections;


Using System.Web;


Using System.Web.Security;


Using System.Web.UI;


Using System.Web.UI.WebControls;


Using System.Web.UI.WebControls.WebParts;


Using System.Web.UI.HtmlControls;


Using System.Xml;


public partial class Ajax_xmlHttpRequest_Result:System.Web.UI.Page


{


protected void Page_Load (object sender, EventArgs e)


{


XmlDocument xmldoc = new XmlDocument ();


Xmldoc.load (Request.inputstream);


XmlNodeList selectedpettypes = Xmldoc.getelementsbytagname ("type");


String type = null;


String responsetext = "Selected Pets:";


for (int i = 0; i &lt; Selectedpettypes.count; i++)


{


Type = Selectedpettypes[i]. Firstchild.value;


ResponseText = ResponseText + "" + type;


}


Response.Write (ResponseText);


Response.End ();


}


}

Then create an XML document, named XMLFile.xml

The code is as follows:

view Plaincopy to Clipboardprint?
01.<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
02.<pet>
<type>mouse</type>
<type>pig</type>
05.</pet>
<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
<pet>
<type>mouse</type>
<type>pig</type>
</pet>


Xml/asp
You can also open the XML document and send it to the ASP page on the server, analyze the request, and return the results.

<body>
<script type= "Text/javascript" >
Xmlhttp=null;
if (window. XMLHttpRequest)
{//code for IE7, Firefox, Opera, etc.
Xmlhttp=new XMLHttpRequest ();
}
else if (window. ActiveXObject)
{//code for IE6, IE5
Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
Xmlhttp.open ("Get", "Note.xml", false);
Xmlhttp.send (NULL);
Xmldoc=xmlhttp.responsetext;

Xmlhttp.open ("POST", "demo_dom_http.asp", false);
Xmlhttp.send (xmldoc);
document.write (Xmlhttp.responsetext);
}
Else
{
Alert ("Your browser does not support XMLHTTP.");
}
</script>
</body>

<%
Set xmldoc = Server.CreateObject ("Microsoft.XMLDOM")
Xmldoc.async=false
Xmldoc.load (Request)

For each x in Xmldoc.documentElement.childNodes
If X.nodename = "to" then Name=x.text
Next
Response.Write (name)
%> returns the result to the client by using the Response.Write property

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.