Sending a GET Request


XMLHttp.open("GET", "phrasebook.txt"); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); 

Sending an HTTP request to a server using XMLHttpRequest consists of the following steps:

1.

Provide the URL and the HTTP verb to use.

2.

Define a callback function when results arrive.

3.

Send the request.

Step 1 can be taken with the open() method of the XMLHttpRequest object. This does notunlike what the method name suggestsactually open an HTTP connection, but just initializes the object. You provide the HTTP verb to use (usually GET or POST) and the URL.

Step 2, the callback function, is provided to the onreadystatechange property of the object. Whenever the readyState property of XMLHttpRequest changes, this callback function is called. Finally, the send() method sends the HTTP request.

In the callback function, the readyState value 4 represents the state of the object we want: call completed. In that case, the responseText property contains the data returned from the server.

Here is a fully working example, sending a GET request to the server (a file called phrasebook.txt with simple text content) and evaluating the response of that call:

Sending a GET Request (xmlhttpget.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"  type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("GET", "phrasebook.txt"); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); function handlerFunction() {   if (XMLHttp.readyState == 4) {     window.alert("Returned data: " +                  XMLHttp.responseText);   } } </script> 

Understating the States of XMLHttpRequest

All in all, the XMLHttpRequest object supports five states, as shown in Table 11.1. Depending on the implementation, up to all of these states happen during the execution of an AJAX script. That is the reason it is so important to always query the state before trying to access other XMLHttpRequest data.

Table 11.1. States of the XMLHttpRequest Object

State

Description

0

Uninitialized

1

Loading

2

Loaded

3

Waiting

4

Complete






JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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