XMLHttpRequestObject


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


实例

Try it - Example

A simple XMLHttpRequest example
Create a simple XMLHttpRequest to retrieve data from a TXT file.

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

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

Retrieve ASP file contents
How does a web page communicate with a web server when the user types characters in an input field?

Retrieve content from the database
How does a web page extract information from a database through 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.


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 web page without reloading the page
  • Request data from a server after a page has loaded.
  • Receive data from a server after a page has loaded.
  • Send data to a server in the background

XMLHttpRequest object methods

Methods Description
abort() Cancel the current request.
getAllResponseHeaders() Return header information.
getResponseHeader() Return the specified header information.
open(method,url,async,uname,pswd) Specifies the type of request, the URL, whether the request should be handled asynchronously, and other optional properties of the request.

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 a request to the server.

string: only used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent.

XMLHttpRequest object properties

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically every time the readyState property changes.
readyState stores the status of XMLHttpRequest. Changes from 0 to 4:
0: Request not initialized
1: Server connection established
2: The received request
3: Handle the request
4: Request completed and response ready
responseText Returns the response data as a string.
responseXML Returns the response data as XML.
status returns the status number (for example, "404" is "Not Found" or "200" is "OK").
statusText returns the status text (such as "Not Found" or "OK").

other extensions