XMLHttpRequestObject


With the XMLHttpRequest object, you can update a part of a webpage without reloading the entire page.


XMLHttpRequest Object

The XMLHttpRequest object is used to exchange data with a server behind the scenes.

The XMLHttpRequest object isDeveloper's Dream, because you can:

  • Update a webpage without reloading the page
  • Request data from a server after the page has loaded
  • Receive data from a server after the page has loaded
  • Send data to a server in the background

Create an XMLHttpRequest object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object

xmlhttp=new XMLHttpRequest();

旧Versionof Internet Explorer(IE5 and IE6)Usage ActiveX Object:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, check whether the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object; if not, create an ActiveX object:

Example

if (window.XMLHttpRequest) { //IE7+, Firefox, Chrome, Opera, Safari 浏览deviceExecuteCode xmlhttp=new XMLHttpRequest(); } else { //Execute code in IE6, IE5 browsers xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

Try it Yourself »


Send a request to the server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();

Methods Description
open(method,url,async) Specifies the type of request, the URL, and whether the request should be handled asynchronously.

method: The type of request: GET or POST
url: The location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string) Send the request to the server.

string: Only for POST requests


GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests in the following cases:

  • Cached files are not an option (update files or database on the server)
  • A large amount of data is sent to the server (POST has no size limit)
  • When sending user input (which can contain unknown characters), POST is more powerful and safer than GET

URL - the file on the server

The url parameter of the open() method is the address of a file on the server:

xmlhttp.open("GET","xmlhttp_info.txt",true);

The file can be any type of file (such as .txt and .xml), or a server script file (such as .html and .php, which can perform actions on the server before sending a response back).


Asynchronous - True or False?

To send the request asynchronously, the async parameter of the open() method must be set to true:

xmlhttp.open("GET","xmlhttp_info.txt",true);

Sending asynchronous requests is a huge improvement for web developers. Many tasks performed on the server are very time-consuming.

By sending asynchronously, JavaScript does not need to wait for the server's response, but can instead:

  • Execute other scripts while waiting for the server's response
  • Handle the response when the response is ready

Async=true

When using async=true, specify a function to be executed when the response is ready in the onreadystatechange event:

Example

xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send();

Try it Yourself »


Async=false

To use async=false, change the third parameter of the open() method to false:

xmlhttp.open("GET","xmlhttp_info.txt",false);

It is not recommended to use async=false, but it is acceptable for handling a few small requests.

Remember that JavaScript will not continue executing until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note:When you use async=false, do not write an onreadystatechange function - just place the code after the send() statement:

Example

xmlhttp.open("GET","xmlhttp_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Try it Yourself »


Server response

To retrieve a response from the server, use the responseText or responseXML property of the XMLHttpRequest object.

Property Description
responseText Get the response data as a string
responseXML The responseXML property returns an XML document object, which can be examined and parsed using the methods and properties of the DOM node tree.


responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:

Example

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Try it Yourself »


responseXML Property

If the response from the server is XML and you want to parse it as an XML object, use the responseXML property:

Example

Request Filecd_catalog.xmland parse the response:

xmlDoc=xmlhttp.responseXML; var txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + ""; } document.getElementById("myDiv").innerHTML=txt;

Try it Yourself »


onreadystatechange event

When a request is sent to the server, we want to perform some actions based on the response.

The onreadystatechange event is triggered whenever readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: Request not initialized
1: Server connection established
2: Received request
3: Process request
4: Request finished and response ready
status 200:"OK"
404: Page not found

In the onreadystatechange event, we specify what will happen when the server's response is ready to be processed.

When readyState is 4 or the status is 200, the response is ready:

Example

xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }

Try it Yourself »

Note:The onreadystatechange event is triggered each time readyState changes, and is triggered a total of four times.


实例s

More Examples

Retrieve header information via getAllResponseHeaders()
Retrieve header information of a resource (file).

Retrieve the specified header information via getResponseHeader().
Retrieves specified header information from a resource (file).

Retrieve ASP file contents
How a web page communicates with a web server when a user types characters in an input field.

Retrieve content from the database
How a web page extracts information from a database using the XMLHttpRequest object.

Retrieve XML file contents
Create an XMLHttpRequest to retrieve data from an XML file and display the data in an HTML table.


other extensions