Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XML DOM - HttpRequest Object

The XMLHttpRequest Object


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


The XMLHttpRequest Object

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

The XMLHttpRequest object is adeveloper's dream, because you can:


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();

Older versions of Internet Explorer (IE5 and IE6) use an 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 browser execution code

xmlhttp

=

new

XMLHttpRequest

(

)

;

}

else

{

//

IE6, IE5 browser execution code

xmlhttp

=

new

ActiveXObject

(

"

Microsoft.XMLHTTP

"

)

;

}

Try it »


Send a request to the server

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

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

xmlhttp.send();

Method Description
open(method,url,async) Specifies the type of request, the URL, and whether the request should be processed asynchronously.
 *method*:请求的类型:GET 或 POST       

 *url*: File location on the server

 *async*:true (asynchronous) or false (synchronous) |

| send(string) | Sends the request to the server.

 *string*:仅用于 POST 请求 |


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:


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 of any type (such as .txt and .xml), or a server script file (such as .html and .php, which can perform actions on the server before sending back a response).


Asynchronous - True or False?

To send a 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 step forward for web developers. Many tasks performed on a server are very time-consuming.

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


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 »


Async=false

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

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

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

Remember that JavaScript will not continue executing until the server's 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 - simply 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 »


Server Response

To get the 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.

The 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 »


The 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 the file cd_catalog.xml and 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 »


The onreadystatechange Event

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

The onreadystatechange event is triggered each time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

property Description
onreadystatechange Stores the 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:请求未初始化       

 1:服务器建立连接       

 2:收到的请求       

 3:处理请求       

 4:请求完成和响应准备就绪 |

| status | 200:"OK"
404: Page not found |

In the onreadystatechange event, we specify what happens 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 »

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


More examples

Retrieve header information with getAllResponseHeaders()
Retrieve the header information of a resource (file).

Retrieve a specified header with getResponseHeader()
Retrieve a specified header of a resource (file).

Retrieve the content of an ASP file
How a web page communicates with a web server when the user types characters into an input field.

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

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