How to Use ajax to develop web applications page 1/2

Source: Internet
Author: User
Tags string back

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

In the past, web applications were restricted due to the need to reload web pages (or load other pages) to obtain new data. Although other methods are available (without loading other pages), these technologies are not well supported and tend to be prone to bugs. In the past few months, a technology that has not been widely supported in the past has been used by more and more web surfers (web surfers ?? Browser or viewer ?) It gives developers more freedom to develop advanced web applications. These applications that use javascript to asynchronously obtain xml data are affectionately called "Ajax applications" (Asynchronous Javascript and XML applications ). In this article, I will explain how to use Ajax to retrieve a remote XML file and update a web page. As this series continues, I will discuss more methods, use ajax technology to upgrade your web applications to a new level.

The first step is to create an XML file with some data. We name this file data. xml. It is a simple XML file, and in a real program, it will be much more complicated, but for our example, simple and clear is the most suitable.

<? Xml version = "1.0" encoding = "UTF-8"?> <Root> <data> This is some sample data, which is saved in an XML file and retrieved by JavaScript. </Data> </root>

Now let's create a simple web page that contains some sample data. This page will be where our js script is located, and this page will let users see the running of Ajax scripts at their access handles. We named the ingress as ajax.html.

<! 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>
</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 id = "xmlObj">
This is some sample data, which is the default data of this web page <a href = "data. xml"
Title = "view the XML data. "onclick =" ajaxRead ('data. xml '); this. style. display = 'none'; return false "> View XML data. </a>
</P>
</Body>
</Html>

Note: For users without javascript, we directly link to the data. xml file. For users who are allowed to run javascript, the function "ajaxRead" will be run, the link will be hidden, and will not be directed to the data. xml file. The function "ajaxRead" is not defined yet. So if you want to verify the above sample code, you will get a javascript error. Let's continue and define this function (there are other ones) so that you can see how ajax works. The following script should be placed in your head Tag:

<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 ){
UpdateObj ('xmlobj ', xmlObj. responseXML. getElementsByTagName ('data') [0]. firstChild. data );
}
}
XmlObj. open ('get', file, true );
XmlObj. send ('');
}
Function updateObj (obj, data ){
Document. getElementById (obj). firstChild. data = data;
}
// --> </Script>

There are a lot of code here, so let's do it a little bit. The first function is called "ajaxRead"-that is, the function we call in the "view XML data" link on the page, we have defined a variable named "xmlObj", which serves as the middleware between the client (the web page that the user is viewing) and the server (the web site itself. We define this object in an if/else block:

If (window. XMLHttpRequest ){
XmlObj = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
XmlObj = new ActiveXObject ("Microsoft. XMLHTTP ");
} Else {
Return;
}

This is just a test of whether different objects are available-Some browsers implement different XMLHttpRequest objects, so when we define "xmlObj" as our XMLHttpRequest object, we have to define it according to what the browser implements. If no XMLHttpRequest object is available, we will execute the "return" statement to end this function to avoid script errors. In most cases, this check will return an XMLHttpRequest object-this part of code should be able to work in most browsers, except for a few exceptions in older browsers (it can work on ie5.01, but it can terminate the function on netscape4 ).

The following code blocks:

XmlObj. onreadystatechange = function (){
If (xmlObj. readyState = 4 ){
UpdateObj ('xmlobj ', xmlObj. responseXML. getElementsByTagName ('data') [0]. firstChild. data );
}
}

Each time the status of XMLHttpRequest changes, the event "onreadystatechange" is triggered. By using "xmlObj. onreadystatechange = function () {...}", we can create a function and run it immediately when the status of the XMLHttpRequest object changes. There are a total of five States, from 0 to 4.

0-Initialization not yet performed (before the XMLHttpRequest starts)

1-Load (XMLHttpRequest initialization ends)

2-Load ended (XMLHttpRequest receives a response from the server)

3-Interaction (when the XMLHttpRequest object is connected to the server)

4-End (when XMLHttpRequest is told that it has completed all characters and stops running)

The fifth state (number 4) is the identifier that can be used to determine whether the data is available. Therefore, we test the xmlObj. whether readyState is equal to "4" to determine whether data is available. If it is 4, run the updateObj function. This function has two parameters: an element ID on the current web page (the element to be updated on the current web page) and the data used to fill this element. The running method of this function will be explained in more detail later.

The p element on our web page has an id "xmlData", which is the section we are going to update. The data we are getting comes from the XML file, but it is a bit complicated. Here is how it works.

The xmlObj. responseXML attribute is a DOM object-it is like a "document" object, except for its remote XML file. In other words, if you run the script in data. xml, xmlObj. responseXML is a "document" object. Because we know this, we can use the "getElementsByTagName" method to retrieve any XML node. Data is contained in an XML node named "<data>", so our task is simple: Get the first (and only this) data node. Therefore, xmlObject. responseXML. getElementsByTagName ("data") [0] returns the first <data> node in the XML file.
Note:It returns the XML node instead of the data in the node. This data must be obtained by accessing the attributes of the XML node. This is what we will talk about next.

Next, you only need to specify "firstChild. data (firstChild points to the text node contained by the <data> node, and the "data" attribute is the actual text of the text node ).

XmlObj. open ('get', file, true );
XmlObj. send ('');

This is the last part of our ajaxRead function. What does it say? Well, the "open" method of xmlObj opens one to the server (through a specified protocol, here it specifies "GET"-you can USE "USE" or other Protocols) (In our example, the variable "file" is assigned to the ajaxRead function-data as a parameter. xml), and javascript can synchronize (false) or asynchronous (true, default) processing requests. Since this is Asynchronous Javascript and XML (AJAX), we will use the default Asynchronous Method-in this example, the synchronous method does not work.

This is the last line in our function. It simply sends an empty string back to the server. Without this line, the readyState of xmlObj will never reach 4, so your page will never be updated. This send method can be used to do other things, but today I am only used to retrieve data from the server-not to send it-so in this article I am not prepared to intervene in any details about the send method.

Function updateObj (obj, data ){
Document. getElementById (obj). firstChild. data = data;
}

Now let's explain a little bit about the updateObj function: This function uses a new value to update any specified element on the current page. Its first parameter, "obj" is the ID of the element on the current page-the object to be updated; its second parameter, "data" is used to replace the content of the object ("obj") with the replaced value. In general, it is wise to check and confirm that the ID of an element on the current page is "obj", but it is not necessary to verify the isolation level of our script. The method for updating this function is similar to that for retrieving data from the "data" node of the XML file-it locates the element to be updated (the ID of this element replaces its label at this time ). name and index on the page) set the data attribute of the first subnode (text node) of this element to a new value. If you need to use HTML instead of plain text to update an element, you can also use

Document. getElementById (obj). innerHTML = data

This is all.

This concept is simple, and the code is not very difficult. You can read a file from somewhere and do not need to reload the web page. You are flexible enough to do a variety of things, including sending data from forms (without reloading web pages) and using a server language to dynamically generate XML files. If you need to be closer, remember that this connection is useful-Oh, remember that Google is your friend. In another article, I will explain how you can use server-side technologies to construct powerful web applications using AJAX.

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.