How to use AJAX to develop Web applications 1th/2 page _ajax related

Source: Internet
Author: User
Tags php script string back

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

In the past, Web application development was limited because of the need to reload Web pages (or load other pages) to get new data. Although there are other methods available (no other pages are loaded), none of these technologies are well supported and have a bug-infested trend. 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). Is it a browser or a visitor? Accepted, it gives developers more freedom to develop advanced Web applications. These applications that obtain XML data asynchronously through JavaScript are affectionately referred to as "Ajax Applications" (asynchronous Javascript and XML applications). In this article, I will explain how to retrieve a remote XML file from Ajax and update a Web page, and as this series continues, I'll discuss more ways to use AJAX technology to elevate your Web application to a new level.

The first step is to create an XML file with some data. We named this file data.xml. It's a simple XML file, and it's a lot more complicated in a real-world program, but for our example, simplicity is the most appropriate.

<?xml version= "1.0" encoding= "UTF-8"?> <root> <data> This is some sample data that 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 our JS script, and this page will let users access the handle to see the Ajax script running. We named it ajax.html

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en"
  "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD"
      <meta http-equiv=" Content-type "content=" text/html; charset=gb2312
    <title> Developing Web applications using AJAX-Example </title>
    <BODY>
        <p > This page demonstrates how Ajax technology updates the content of a Web page by dynamically reading a remote file-no need to reload any pages. Note: This example is not effective for users who prohibit JS. </p>
    <p id= "Xmlobj"
    This is some sample data, which is the default data for this page <a href= " Data.xml "
    title=" To view this XML data. "Onclick=" Ajaxread (' Data.xml '); this.style.display= ' None '; return false > View XML data. </A>
    </p>
  </body>

Note that for those users who do not have JavaScript, we are directly linked to the Data.xml file. For those who allow JavaScript to run, the function "Ajaxread" will be run, the link is hidden, and will not be diverted to the Data.xml file. The function "Ajaxread" is not defined yet. So if you want to verify the example code above, you'll get a JavaScript error. Let's go ahead and define this function (and others) so that you can see how Ajax works, and the following script goes to 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>

This pile of code is a little bit more, let's do it a little bit. The first function is called "ajaxread"-the function we call in the "View XML data" link in the page, and we define a "xmlobj" variable-which will act as a middleware between the client (the Web page that the user is viewing) and the service side (the Web site itself). We define this object in a 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 there are no XMLHttpRequest objects available, we will execute the "return" statement to end this function to avoid scripting errors. In most cases, this test will return a XMLHttpRequest object-this part of the code should be able to work on most browsers, except for the exception of a few older browsers (it works on ie5.01, but the function terminates on Netscape4).

Next, these blocks of code:

Xmlobj.onreadystatechange = function () {
if (xmlobj.readystate = = 4) {
Updateobj (' Xmlobj ', xmlObj.responseXML.getElementsByTagName (' data ') [0].firstchild.data);
}
}

Each time the XMLHttpRequest state changes, the event "onreadystatechange" is triggered. By using the "Xmlobj.onreadystatechange = function () {...}" We can create a function and let it run immediately when the state of the XMLHttpRequest object changes every time. There are a total of five states, from 0 to 4.

0 – not initialized (before this xmlhttprequest starts)

1 – Loading (XMLHttpRequest initialization one end)

2 – load End (XMLHttpRequest a response from the server)

3 – interaction (when the XMLHttpRequest object and server are connected)

4 – End (when XMLHttpRequest is told that it has completed all the characters and ends the run)

This fifth state (the number 4) is the flag that we can determine that the data is available, so we check whether the xmlobj.readystate equals "4" to determine whether the data is available, and if it is 4, we run the Updateobj function. This function takes two parameters: the element ID of the current Web page (the element to be updated on the current web page) and the data used to populate the element. The way this function is run will be explained in more detail later.

The P element of our web page has an id "XmlData", which is the paragraph we are going to update. The data we're getting is from the XML file, but it's a bit complicated. Here is the principle of how it works.

The Xmlobj.responsexml property is a DOM object-it is very much like a "document" object, except that it comes from a remote XML file. In other words, if you run a script in Data.xml, that Xmlobj.responsexml is a "document" object. Because we know this, we can get any XML nodes through the "getElementsByTagName" method. The data is contained in an XML node named "<data>", so our task is simple: Get the first (and only this) data node. Thus, xmlObject.responseXML.getElementsByTagName ("data") [0] returns the first <data> node in the XML file.
Note: it returns an XML node, not the data in the node-this data must be obtained by accessing the attributes of the XML node, which is what to say next.

The next step is to simply specify "Firstchild.data" (firstchild points to the text node contained in 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 did it say? Well, Xmlobj's "open" method opens a to the server (through a specified protocol, where you specify "get" – you can use the connection of "using" or any other protocol) to request a file (in our case, the variable "file" is assigned as a parameter to the Ajaxread function-data.xml), and JavaScript can synchronize (false) or asynchronous (true, default) processing requests. Since this is asynchronous JavaScript and XML (AJAX), we'll use the default asynchronous approach--in this case, using the Sync method will not work.

This is the last line in our function, which simply sends an empty string back to the server. Without this line, Xmlobj's readystate will never be 4, so your page will never be updated. This send method can be used for other things, but today I'm just using it to get data from the server-not send it-so in this article I'm not going to get involved in any details about the Send method.

function updateobj (obj, data) {
document.getElementById (obj). firstchild.data = data;
}

Now explain a little bit about the Updateobj function: This function uses a new value to update any specified element on the current page. His first argument, "obj" is the object of the element in the current page that is to be updated, and its second argument, "data", is used to replace the contents of the object ("obj") that will be substituted for the value of the id-. In general, it would be wise to examine and determine that the ID of an element on the current page is "obj", but that verification is not necessary for this isolation level of our script. This function is updated in the same way that we got the data from the "Data" node of the XML file-it locates the element that it wants to update (the ID of this element replaces its label name and the index on the page) and sets the data property of the first child node (text node) of this element to the new value. If you need to update an element using HTML instead of plain text, you can also use the

document.getElementById (obj). InnerHTML = Data

That's all.

The concept is simple, and the code is not very difficult. You can read a file from somewhere and don't need to reload the Web page. You have the flexibility to do all sorts of things, including sending data from a form (you don't need to reload a Web page) and using a server-side language to dynamically generate XML files. If you need a step closer, remember that this connection is useful-oh, and remember that Google is your friend. In another article, I'll explain how you can use Ajax to build powerful Web applications with server-side technology.

About the author

Jonathan Fenocchi (mail:jona#slightlyremarkable.com #换成 @) is a web developer, the main website design, client script, PHP script.
His site is located in: http://www.slightlyremarkable.com

Current 1/2 page 12 Next read the full text
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.