How to Use ajax to develop web applications 2

Source: Internet
Author: User

In the previous article, we discussed how to use javascript to retrieve data from a remote XML file. In this article, we will learn how to perform more complex data processing. As an example, we prepare a set of XML data, divide the data into independent fragments, and display these fragments in different ways (depending on how they are identified ).

This article is based on the sample code constructed in the previous article, so if you cannot understand our current code, you can read the first article (sheneyan note: ).

Start ~

Let's start our first step: Construct XML. We are preparing to write an XML document, which organizes a series of data to be processed by javascript, so we will organize some nodes and subnodes (or, elements and subelements) together ). In this example, we will use the names of some family pets:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Data>
<Pets>
<Pet> CAT </pet>
<Pet> dog </pet>
<Pet> fish </pet>
</Pets>
</Data>

In the above, we have this XML Declaration (indicating this document is an XML 1.0 document, encoded using a UTF-8), a root element (<data>) combines all the following elements, A <pets> element organizes all pets, and then a <pet> node corresponds to a pet. To specify the type of animal each pet belongs to, we set the text node: cat, dog, and fish in the <pet> element.

<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 // EN"
Http://www.w3.org/TR/html4/strict.dtd>
<Html lang = "zh" dir = "ltr">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> Use Ajax to develop Web applications-example </title>
<Script type = "text/javascript"> <! --
Function ajaxRead (file ){
Var xmlObj = null;
If (window. XMLHttpRequest ){
XmlObj = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
XmlObj = new ActiveXObject ("Microsoft. XMLHTTP ");
} Else {
Return;
}
Xmlobj. onreadystatechange = function (){
If (xmlobj. readystate = 4 ){
Processxml (xmlobj. responsexml );
}
}
Xmlobj. Open ('get', file, true );
Xmlobj. Send ('');
}
Function processxml (OBJ ){
VaR dataarray = obj. getelementsbytagname ('Pet ');
VaR dataarraylen = dataarray. length;
Var insertData = '<table style = "width: 150px; border: solid 1px #000"> <tr> <th>'
+ 'Pets </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
InsertData + = '<tr> <td>' + dataArray [I]. firstChild. data + '</td> </tr> ';
}
InsertData + = '</table> ';
Document. getElementById ('dataare'). innerHTML = insertData;
}
// --> </Script>
</Head>
<Body>
<H1> Use Ajax to develop web applications <P> This page demonstrates how Ajax technology dynamically reads a remote file to update the content of a webpage-without reloading any webpage. Note: This example does not work for users who disable javascript. </P>
<P> This page shows how to retrieve and process XML data in groups. The retrieved data is output in a table.
<A href = "#" onclick = "ajaxread ('data _ 2. xml'); Return false"> View demo </a>. </P>
<Div id = "dataarea"> </div>
</Body>
</Html>

(Sheneyan NOTE: For the complete code example, see example_2.html. For the XML file, see data_2.xml)

You will notice that we call this function in the same way (via a hyperlink) as we did last time, and we put the data into a div (this time this stuff is called "dataarea "). This ajaxread () function is very similar to the previous one, except for the onreadystatechange function. Let's take a look at this function first:

Xmlobj. onreadystatechange = function (){
If (xmlobj. readystate = 4 ){
Processxml (xmlobj. responsexml );
}
}

We canceled the updateObj function and replaced it with a new function called processXML. This function will get the XML document itself (that is, it is retrieved by the ajaxRead function) and process it. (This "XML document itself" refers to the parameter "xmlObj. responseXML ")

Now let's analyze this function processXML. The following is its code:

Function processXML (obj ){
Var dataArray = obj. getElementsByTagName ('Pet ');
Var dataArrayLen = dataArray. length;
Var insertData = '<table style = "width: 150px; border: solid 1px #000"> <tr> <th>'
+ 'Pets </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
InsertData + = '<tr> <td>' + dataArray [I]. firstChild. data + '</td> </tr> ';
}
InsertData + = '</table> ';
Document. getElementById ('dataare'). innerHTML = insertData;
}

First, we define some variables. "DataArray" serves as an array of all <pet> nodes (not node data, but nodes ). "DataArrayLen" is the length of this array for our loop. "InsertData" is the HTML at the beginning of a table.

The second step is to traverse all the <pet> elements (via the "dataArray" variable) and add the data to the variable insertData. Here we will create a table row, insert a table data node (td), and then include the text of each <pet> element into this table data node, and add these to the variable "insertData ". Therefore, every cycle is performed, the variable insertData adds a new row containing one of the three pets.

After the new data row is added, we insert a "</table>" end tag to the variable "insertData ". This completes the table, and I only have this last step to achieve our goal: we need to put this table on the page. Fortunately, thanks to the innerHTML attribute, this is simple. The document. getElementById () function is used to obtain the DIV "dataArea" and insert the HTML in the variable "insertData. Well, this form is coming up!

Before we proceed ......

I have to point out two points:

First, you will notice that we are not using the node <pets>. This is because we only have one data group (<pets>) and all later elements (each <pet> element ); these subnodes contain different data but have the same name. In this example, this node can be ignored. However, it is better to put all the <pet> elements into the <pets> element, rather than letting the <pet> elements scatter themselves (but still in the data element ).

Another way is to place a specified tag for each pet, for example:

<? XML version = "1.0" encoding = "UTF-8"?>
<DATA>
<Pets>
<CAT/>
<Dog/>
<Fish/>
</Pets>
</Data>

Then we can traverse the nodes in the <pets> element. The processxml function looks like this:

Function processxml (OBJ ){
VaR dataarray = obj. getelementsbytagname ('pets') [0]. childnodes;
VaR dataarraylen = dataarray. length;
VaR insertdata = '<Table Style = "width: 150px; Border: solid 1px #000"> <tr> <TH>'
+ 'Pets </Th> </tr> ';
For (VAR I = 0; I <dataarraylen; I ++ ){
If (dataarray [I]. tagname ){
Insertdata + = '<tr> <TD>' + dataarray [I]. tagname + '</TD> </tr> ';
}
}
Insertdata + = '</table> ';
Document. getelementbyid ('dataare'). innerhtml = insertdata;
}

(Sheneyan NOTE: For the modified example, see example_2_1.html. For the XML file, see data_2_1.xml)

The modification here points to the <pets> group element (this "[0]" means this is the first one, even if it is the only one) and its sub-nodes (elements <CAT/>, <dog/>, and <fish/> ). Because text elements divide these elements (spaces are considered to be a node), we need to determine that only those nodes with label names pass through (well, that is, only labels. Then we output the name of each tag. Because each label name is a pet, we do not need to obtain the data of each node-the node name itself is sufficient. Let's see how it works.

Another way is to set an attribute value for each <pet> node. Your XML document looks like this:

<? XML version = "1.0" encoding = "UTF-8"?>
<Data>
<Pets>
<Pet type = "cat"/>
<Pet type = "dog"/>
<Pet type = "fish"/>
</Pets>
</Data>

You only need to slightly modify your processXML function, which becomes like this:

Function processXML (obj ){
Var dataArray = obj. getElementsByTagName ('Pet ');
Var dataArrayLen = dataArray. length;
Var insertData = '<table style = "width: 150px; border: solid 1px #000"> <tr> <th>'
+ 'Pets </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
InsertData + = '<tr> <td>' + dataArray [I]. getAttribute ('type') + '</td> </tr> ';
}
InsertData + = '</table> ';
Document. getElementById ('dataare'). innerHTML = insertData;
}

(Sheneyan NOTE: For the modified example, see example_2_2.html. For the XML file, see data_2_2.xml)

The key difference is that we get a value through dataArray [I]. getAttribute ('type'), which returns the value of the "type" attribute of the current <pet> node.

Continue...

Now we know some effective ways to retrieve data from a separate XML data group. Let's see how to retrieve data from multiple groups. Unlike listing what a pets has, we assume that we have a daily schedule for our pets. Because they all have different needs, each pet needs to be carefully taken care. In the face of this situation, the animal viewer needs a daily basis. Now let's put these in a well-formatted XML:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Data>
<Pets>
<Pet> Cat
<Task> Feed </task>
<Task> Water </task>
<Task> Comb out fleas </task>
</Pet>
<Pet> Dog
<Task> Feed </task>
<Task> Water </task>
<Task> Put outside </task>
</Pet>
<Pet> Fish
<Task> Feed </task>
<Task> Check oxygen, water purity, etc. </task>
</Pet>
</Pets>
</Data>

This may seem strange, but this is the sub-group we are creating ). Each <pet> element is a sub-group of <pets>, and each <task> is a sub-element of each <pet> group.

Before I continue, you may want to beautify your table with some css, such:

<Style type = "text/css"> <! --
Table, tr, th, td {
Border: solid 1px #000;
Border-collapse: collapse;
Padding: 5px;
}
--> </Style>

This makes the table easier to read. Now let's study the processXML function:

Function processXML (obj ){
Var dataArray = obj. getElementsByTagName ('Pet ');
Var dataArrayLen = dataArray. length;
Var subAry, subAryLen;
Var insertData = '<table> <tr> <th>'
+ 'Pets </th> <th> Tasks </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
InsertData + = '<tr> <td>' + dataArray [I]. firstChild. data + '</td> ';
SubAry = dataArray [I]. getElementsByTagName ('task ');
SubAryLen = subAry. length;
InsertData + = '<td> ';
For (var j = 0; j <subAryLen; j ++ ){
InsertData + = subAry [j]. firstChild. data;
If (subarylen! = J + 1) {insertdata + = ',';}
}
Insertdata + = '</TD> </tr> ';
}
Insertdata + = '</table> ';
Document. getelementbyid ('dataare'). innerhtml = insertdata;
}

(Sheneyan NOTE: For the modified example, see example_2_3.html. For the XML file, see data_2_3.xml)

The newly added content is the declaration of two new variables: "subary" and "subarylen ". They are similar to the previous variables "dataarray" and "dataarraylen, except that they point to different arrays (especially those "task" elements-when "dataarray" and "dataarraylen" point to "Pet" elements ).

We also changed the initial value of the variable "insertdata"-We added a table header (<TH>) to our "tasks" field.

The next change lies in the Loop: We assign the value to the subary and subarylen variables. The subary variable becomes the array of the <task> element of the current <pet>. The subarylen variable becomes the length of the array until the array changes (when the external loop goes to the next <pet> ).

We have created an embedded loop to process all the <task> elements, one at a time. In general, we create a new data grid, put it into a list of tasks separated by commas, and then close the data table and the current row. In particular, the <task> element node data (the task itself, such as "feeding") is placed into the data lattice in the variable "insertData.

Next, we will check whether <pet> has more tasks. If there is, we add a comma (,) to the variable insertData to separate each task with a comma (,) ("a, B, c", instead of "a, B, c, "-note that the last comma is in the second task, so we do not need ). This is done when we get the subAry array length (add 1 to the "j" variable of the loop. Because this loop will increase the variable "j" by 1 in the next loop, and "j" will be 1 more than this test. Therefore, if "j + 1" (or, "j value when the loop starts again") is equal to subAryLen (number of <task> nodes of the current <pet> node ), this loop stops. If the loop is no longer running, we will not add new commas to separate tasks. Therefore, if "j + 1" is not equal to subAryLen, we can safely Add a comma to "insertData" to prepare for the next <task>.

Once the internal loop ends, we close the task data lattice and the pet row. The External Loop creates a new row and moves it to the next <pet>. This process continues until all <pet> elements (and all <task> elements of each pet) are processed.

Is there any other method?

You may think: "javascript becomes quite complicated, but it will only become complicated as XML becomes more and more complex. Maybe we can simplify XML and then simplify javascript ". If you think so, it would be great because you are completely correct. One of the different methods I have previously demonstrated may be the most appropriate one I have explained in detail. How can we use attributes to correspond to each pet and corresponding tasks? What does XML look like?

<? Xml version = "1.0" encoding = "UTF-8"?>
<Data>
<Pets>
<Pet type = "Cat" tasks = "Feed, Water, Comb out fleas"/>
<Pet type = "Dog" tasks = "Feed, Water, Put outside"/>
<Pet type = "Fish" tasks = "Feed, Check oxygen, water purity, etc."/>
</Pets>
</Data>

Wow! It looks much simpler. Let's take a look at how our processXML function is modified:

Function processXML (obj ){
Var dataArray = obj. getElementsByTagName ('Pet ');
Var dataArrayLen = dataArray. length;
Var insertData = '<table> <tr> <th>'
+ 'Pets </th> <th> Tasks </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
InsertData + = '<tr> <td>' + dataArray [I]. getAttribute ('type') + '</td>'
+ '<Td>' + dataArray [I]. getAttribute ('task') + '</td> </tr> ';
}
InsertData + = '</table> ';
Document. getElementById ('dataare'). innerHTML = insertData;
}

(Sheneyan NOTE: For the modified example, see example_2_4.html. For the XML file, see data_2_4.xml)

Just as you guessed, functions are much simpler. Because the code becomes simpler, it becomes more efficient. The only difference from our old function is that this variable insertData now inserts more HTML, especially the two new variables "type" and "tasks ". As we learned earlier, those attributes are obtained from the <pet> element of the XML document, and each pet attribute has different values. It may be the easiest way for you to modify the XML file to adapt to changes in your progress. For example, if you finally get rid of the flea on your cat, you just need to simply delete the "reduce flea count" from your cat's daily task table, however, in the XML we used earlier, the implementation may be confused.

The final XML formatting method is to mix the two parts. Now we will use properties and different labels. Let's take a look at the example XML:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Data>
<Pets>
<Cat tasks = "feeding, drinking water, reducing flea count"/>
<Dog tasks = "feeding, drinking water, walking out"/>
<Fish tasks = "feeding, checking oxygen, purity of water, others"/>
</Pets>
</Data>

This is perhaps the most understandable XML. Let's analyze the changes we made to make the processXML function operate:

Function processXML (obj ){
Var dataArray = obj. getElementsByTagName ('pets') [0]. childNodes;
Var dataArrayLen = dataArray. length;
Var insertData = '<table> <tr> <th>'
+ 'Pets </th> <th> Tasks </th> </tr> ';
For (var I = 0; I <dataArrayLen; I ++ ){
If (dataArray [I]. tagName ){
InsertData + = '<tr> <td>' + dataArray [I]. tagName + '</td>'
+ '<Td>' + dataArray [I]. getAttribute ('task') + '</td> </tr> ';
}
}
InsertData + = '</table> ';
Document. getElementById ('dataare'). innerHTML = insertData;
}

(Sheneyan NOTE: For the modified example, see example_2_5.html. For the XML file, see data_2_5.xml)

"DataArray" now points to the <pets> subnodes and treats them as an array (in other words, dataArray is now an array of all nodes in the <pets> node ). This is because every tag is different (<CAT/>, <dog/>, <fish/> ), therefore, we cannot use the names of these elements to search for them (Instead, we can use <pet> because all elements are <pet> ).

In the same way, there are spaces between each node, so we can exclude text nodes during our processing. We can check whether the label name exists-the text node is a node but there is no label, while the <CAT/>, <dog/>, <fish/> nodes are all labels. So if a tag has a name, we can insert the data into the variable insertData. The data we inserted is a table with two data cells. The first cell is the label name, that is, the type of the PET (cat, dog, or fish ), the second cell specifies the animal's "tasks" attribute value (such as "feeding or drinking water ").

Conclusion

In this article, I have demonstrated many changes in this example. You can test them at will to determine which one is more suitable for you. Remember that XML is "extensible", so there is no "wrong" way to combine your data, although there is often a "best" method. In addition, make sure that your XML format is good. Remember that a lot of problems come from forgetting to end a tag (for example, <dog/> instead of <dog>; unless there is data in this node, for example, the following <dog> data here </dog> ).

My intention is to make the XML and javascript applications clearer without being confused. Step-by-Step learning to process more data, you can apply ajax for a larger purpose. I want to see more ajax applications for enterprise websites and others. So if you apply this knowledge to practice, I'm glad to know what you learned (mail: jona # slightlyremarkable.com # Replace @).

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.