What Is JavaScripts Place in Ajax?


What Is JavaScript’s Place in Ajax?

Where does JavaScript belong in the scheme of things? It turns out that it’s absolutely central; JavaScript is what makes Ajax work. To see that, take a look at an example.

This example downloads and displays text from a server. (You’ll see what makes it tick in detail in the next chapter.) You can see this example in a Web browser in Figure 2.1.

image from book
Figure 2.1: An Ajax demo

When this application is hosted on a Web server, clicking the Fetch the Message button causes the application to use Ajax techniques behind the scenes to connect to the server and download the contents of a text file, data.txt. Here’s what’s in data.txt:

 This text was fetched from the server with Ajax.

Clicking the button downloads the message from the server, without any page refresh needed. The downloaded text simply appears, as shown in Figure 2.2.

image from book
Figure 2.2: Downloading text using Ajax

You already know that this example just uses a simple text file, data.txt, on the server, so the whole magic must be in the Web page, index.html, itself. It is, and it’s in JavaScript. Here’s what that JavaScript looks like in index.html:

 <html>   <head>     <title>An Ajax demo</title>     <script language = "javascript">       var XMLHttpRequestObject = false;       if (window.XMLHttpRequest) {         XMLHttpRequestObject = new XMLHttpRequest();       } else if (window.ActiveXObject) {         XMLHttpRequestObject = new           ActiveXObject("Microsoft.XMLHTTP");       }       function getData(dataSource, divID)       {         if(XMLHttpRequestObject) {           var obj = document.getElementById(divID);           XMLHttpRequestObject.open("GET", dataSource);           XMLHttpRequestObject.onreadystatechange = function()           {             if (XMLHttpRequestObject.readyState == 4 &&               XMLHttpRequestObject.status == 200) {                 obj.innerHTML =                   XMLHttpRequestObject.responseText;             }           }           XMLHttpRequestObject.send(null);         }       }     </script>   </head>   <body>     <H1>An Ajax demo</H1>     <form>       <input type = "button" value = "Fetch the message"         onclick = "getData('data.txt', 'targetDiv')">     </form>     <div >       <p>The fetched message will appear here.</p>     </div>   </body> </html>

As you can see, nearly all of what’s going on here is JavaScript. JavaScript is the basis of this application, as it is of many Ajax applications. In fact, the starting point for any discussion of Ajax programming is JavaScript, so it’s time to launch into JavaScript, starting with a little background.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net