Chapter 3 of ajax basic reading notes (sending requests and processing responses)

Source: Internet
Author: User

Use XMLHttpRequest. responsexml;

Resolve the response to XML

The following attributes and methods are available for obtaining objects:

 

Table 3-1 process Dom element attributes of an XML document

 

 

Attribute name
Description
 
Childnodes
Returns an array of all child elements of the current element.
 
Firstchild
Returns the first subelement of the current element.
 
Lastchild
Returns the last child element of the current element.
 
Nextsibling
Returns the elements that follow the current element.
 
Nodevalue
Specifies the read/write attribute of the element value.
 
Parentnode
Returns the parent node of an element.
 
Previussibling
Returns the element adjacent to the current element.
 

Table 3-2 Dom element methods used to traverse XML documents

Method Name
Description
 
GetElementById (id) (document)
Obtain the elements in the document with the specified unique ID property value
 
GetElementsByTagName (name)
Returns an array of child elements with specified names in the current element.
 
HasChildNodes ()
Returns a Boolean value indicating whether the element has a child element.
 
GetAttribute (name)
Returns the attribute value of an element. The attribute is specified by name.

 

Let's look at an instance.

 

The following example shows how easy it is to read XML documents using JavaScript following W3C DOM. Code List 3-3 shows the content of the XML document returned by the server to the browser. This is a simple list of U.S. states, divided by region.

Code List 3-3 List of U.S. states returned by the server

Here is an xml

<? Xml version = "1.0" encoding = "UTF-8"?>

<States>

<North>

<State> Minnesota </state>

<State> Iowa </state>

<State> North Dakota </state>

</North>

<South>

<State> Texas </state>

<State> Oklahoma </state>

<State> Louisiana </state>

</South>

<East>

<State> New York </state>

<State> North Branch Lina </state>

<State> mascript usetts </state>

</East>

<West>

<State> California </State>

<State> Oregon </State>

<State> Nevada </State>

</West>

</States>

An HTML page with two buttons is generated in the browser. Click the first button to load the XML document from the server, and then display all States listed in the document in the warning box. Click the second button to load the XML document from the server, but only the States in the Northern Region are displayed in the warning box (see Figure 3-2 ).

 

Figure 3-2 Any button on the page loads the XML document from the server and displays the appropriate results in the warning box.

Code example 3-4 shows parsexml.html.

Code List 3-4 parsexml.html

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 strict // en"

Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>

<HTML xmlns = "http://www.w3.org/1999/xhtml">

<Head>

<Title> parsing XML responses with the W3C Dom </title>

 

<SCRIPT type = "text/JavaScript">

VaR XMLHTTP;

VaR requesttype = "";

 

Function createxmlhttprequest ()

{

If (window. activexobject)

{

XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");

}

 

Else if (window. XMLHttpRequest)

{

XMLHTTP = new XMLHttpRequest ();

}

}

 

Function startrequest (requestedlist)

{

Requesttype = requestedlist;

Createxmlhttprequest ();

XmlHttp. onreadystatechange = handleStateChange;

XmlHttp. open ("GET", "parseXML. xml", true );

XmlHttp. send (null );

}

 

Function handleStateChange ()

{

If (xmlHttp. readyState = 4)

{

If (xmlHttp. status = 200)

{

If (requestType = "north ")

{

ListNorthStates ();

}

Else if (requestType = "all ")

{

ListAllStates ();

}

}

}

}

 

Function listNorthStates (){

Var xmlDoc = xmlHttp. responseXML;

Var northNode = xmlDoc. getElementsByTagName ("north") [0];

 

Var out = "Northern States ";

Var northStates = northNode. getElementsByTagName ("state ");

 

OutputList ("Northern States", northStates );

}

 

Function listAllStates (){

Var xmlDoc = xmlHttp. responseXML;

Var allStates = xmlDoc. getElementsByTagName ("state ");

 

OutputList ("All States in Document", allStates );

}

 

Function outputList (title, states ){

Var out = title;

Var currentState = null;

For (var I = 0; I <states. length; I ++ ){

CurrentState = states [I];

Out = out + "/n-" + currentState. childNodes [0]. nodeValue;

}

Alert (out );

}

</Script>

</Head>

 

<Body>

<H1> Process XML Document of U. S. States

<Br/>

<Br/>

<Form action = "#">

<Input type = "button" value = "View All Listed States"

Onclick = "startRequest ('all');"/>

<Br/>

<Br/>

<Input type = "button" value = "View All Listed Northern States"

Onclick = "startrequest ('north');"/>

</Form>

</Body>

</Html>

 

Resolution:

The listnorthstates and listallstates functions are different. They use the responsexml attribute of the XMLHTTPRequest object and obtain the result as an XML document. In this way, you can use the W3C DOM method to traverse XML documents.

 

Take a closer look at the listallstates function. It first creates a local variable named xmldoc and initializes the variable to the XML document returned by the server. This XML document is obtained using the responsexml attribute of the XMLHTTPRequest object. The getelementsbytagname method of the XML document can be used to obtain all elements marked with state in the document. The getelementsbytagname method returns an array containing all State elements. This array is assigned to a local variable named allstates.

 


The listNorthStates function is similar to listAllStates, but it adds a small trick. You only want the state in the Northern Region, not all States. Therefore, you must first use the getElementsByTagName method to obtain the north element in the XML document. Because the document only contains one north element, and the getElementsByTagName method always returns an array, use the [0] method to extract the north element. This is because, in the array returned by the getElementsByTagName method, the north element is in the first position (also the only position ). Now that the north element is available, call the getElementsByTagName method of the north element to obtain the state sub-element of the north element. With an array of all state sub-elements of the north element, use the outputList method to display these state names in the warning box.


 

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.