Web Standard/JavaScript

XMLHttpRequest Object

seevaa 2011. 5. 15. 17:05

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

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:

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

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

Example

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

Send a Request To a Server

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

  • open(method,url,async) : Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
    • method: the type of request: GET or POST
    • url: the location of the file on the server
    • async: true (asynchronous) or false (synchronous)
    xmlhttp.open("GET","xmlhttp_info.txt",true);
  • send(string) : Sends the request off to the server.
    • string: Only used for POST requests
    xmlhttp.send();