How to Use ajax to develop web application 3

Source: Internet
Author: User

Author:Jonathan Fenocchi
Time:2005.10.25
Translator:Sheneyan
Original English:
Http://webreference.com/programming/javascript/jf/column12/index.html

In the third part of the AJAX series, we will learn how to use AJAX to write with the server and how these technologies generate powerful web applications. If you are interested in learning how to build web programs like GMail or Google Maps, this is a basic introduction (although the two things are much more complicated than the content we mentioned in this article ). In this article, I use PHP as the server language, but AJAX is compatible with any server language, so you can choose any language you like!

We started our learning from the code in the previous article. You can read it for reference.

Here is the HTML page (with js ):

<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 // EN"
Http://www.w3.org/TR/html4/strict.dtd>
<Html lang = "zh-cn" dir = "ltr">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1">
<Title> How to 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 ('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;
}
// --> </Script>
<Style type = "text/css"> <! --
Table, tr, th, td {
Border: solid 1px #000;
Border-collapse: collapse;
Padding: 5px;
}
--> </Style>
</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 _ 3. php'); return false"> View demo </a>. </p>
<Div id = "dataArea"> </div>
</Body>
</Html>

(Sheneyan Note: For examples, see example_3.html)
Note: The only change here is that we changed "data_2.xml" in our ajaxRead () to "data_3.php ". This is because we will use php to output XML (if you open this php file in your browser, it will be displayed in the form of an XML file-we just want to operate in this file, not just a simple XML ). The output of this PHP file is similar:

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

(Sheneyan note: the example is not provided. Please refer to the following description .)

This is only the output result. We are going to get this information from a mysql database. From now on, we can modify the data directly in our database instead of manually modifying the XML file. Use AJAX to retrieve data through PHP and get it to a page-all of which still do not need to be reloaded.

The first step is to connect to mysql to obtain data. This article focuses on javascript, so I won't explain how the following code works. You need to know how to connect to the mysql database by yourself.

<? Php
$ User = "admin ";
$ Pass = "adminpass ";
$ Host = "localhost ";
$ Conn = mysql_connect ($ host, $ user, $ pass) or die ("Unable to connect to MySQL .");
$ Db = mysql_select_db ("pets", $ conn) or die ("cocould not select the database .");
Mysql_close ($ db );
?>

As long as you connect to the database, you can obtain information through the following query:

<? Php
$ User = "admin ";
$ Pass = "adminpass ";
$ Host = "localhost ";
$ Conn = mysql_connect ($ host, $ user, $ pass) or die ("Unable to connect to MySQL .");
$ Db = mysql_select_db ("pets", $ conn) or die ("cocould not select the database .");
$ Result = mysql_query ("SELECT * FROM 'pets '");
If (mysql_num_rows ($ result) = 0 ){
Die ('error: no data found in the database .');
}
While ($ row = mysql_fetch_assoc ($ result )){
Echo 'Pet: '. $ row ['Pet']. ', tasks:'. $ row ['task']. '.';
}
 
Mysql_close ($ db );
?>

This Code provides the information you need, but the output is incorrect. We need to modify the PHP code to separate the data into XML, rather than plain text. We have to make several modifications to achieve this goal.

<? Php
Header ('content-Type: text/xml'); // Id 1
Echo '<? Xml version = "1.0" encoding = "UTF-8"?> '; // Number 2
Echo "\ n <data> \ n <pets> \ n"; // 3
$ User = "admin ";
$ Pass = "adminpass ";
$ Host = "localhost ";
$ Conn = mysql_connect ($ host, $ user, $ pass) or die ("unable to connect to mysql .");
$ Db = mysql_select_db ("pets", $ conn) or die ("unable to select database .");
$ Result = mysql_query ("SELECT * FROM 'pets '");
If (mysql_num_rows ($ result) = 0 ){
Die ('error: no data in the database .');
}
While ($ row = mysql_fetch_assoc ($ result )){
Echo '<'. $ row ['Pet ']. 'tasks = "'. $ row ['tasks']. '"/> '. "\ n"; // number 4
}
Echo "</pets> \ n </data>"; // number 5
Mysql_close ($ db );
?>

Let's start from the above and analyze how XML is output in one row at a time. I added comments to each line for better understanding (the original article is I 've color-coded each line to make it easier to understand, I am too lazy to color, change to the serial number)

1: This part of the code sends an http header to let the user client understand that the PHP file outputs an XML file. This is why when you read this document in your browser, it is displayed as an XML file, even if your file has a ". php" suffix.

2: This part of the code outputs the XML declaration. This is the first line of XML that I showed you before.

3: The first two labels output by the Code: Our root tag, <data> and the <pets> tag we use to place all pets.

4: This part of the code is the most difficult. This contains a loop used to traverse all the data in your database. Each cycle outputs a new node, which uses each animal as the label name and a "task" attribute. For example, if the first pet in your database is a "cat" and its corresponding task field is "feeding, drinking water, catching flea ", then php will output in the XML document <cat tasks = "feeding, drinking water, catching flea"/>. The "\ n" part only inserts a new line at the end to ensure that the XML Code is not in the same line.

5: This part of the code ends the </pets> and </data> nodes opened at the beginning. Because XML must be well-formed, we must take this part seriously to ensure that our program runs properly.

Now we have made PHP output XML. What we need to do now is to log on to our mysql database and make necessary modifications to update this XML. It's cool, isn't it? We can still use the js script in the previous article to get the code, because the XML output is exactly the same as the previous one.

Conclusion

You can use XML to save and retrieve data for further extension. In other words, you can use php to write your XML file and then use javascript to read it. With ajax, you can also regularly check whether the xml file has been changed. If the XML file has been updated, you can also update this page.

About the author

Jonathan Fenocchi (mail: jona # slightlyremarkable.com # replaced by @) is a network developer who focuses on web design, client scripts, and php scripts.
His website is located in: http://www.slightlyremarkable.com

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.