Java Reference
In-Depth Information
using the xmlhttprequest oBjeCt
As stated before, you can create Ajax‐enabled applications in a variety of ways. However, probably
the most popular Ajax technique incorporates the JavaScript
XMLHttpRequest
object, which is
present in all major browsers.
Note
Despite its name, you can retrieve other types of data, like plaintext,
with
XMLHttpRequest
.
The
XMLHttpRequest
object originated as a Microsoft component, called
XmlHttp
, in the MSXML
library first released with IE 5. It offered developers an easy way to open HTTP connections and
retrieve XML data. Microsoft improved the component with each new version of MSXML, making
it faster and more efficient.
As the popularity of the Microsoft
XMLHttpRequest
object grew, Mozilla decided to include its
own version of the object with Firefox. The Mozilla version maintained the same properties and
methods used in Microsoft's ActiveX component, making cross‐browser usage possible. Soon after,
Opera Software and Apple copied the Mozilla implementation, and Google naturally implemented
it with Chrome's initial release. As for Internet Explorer,
XMLHttpRequest
is no longer an ActiveX
component but a native object in the browser.
Creating an xmlhttprequest object
The
XMLHttpRequest
object is located in the
window
object. Creating an
XMLHttpRequest
object is
as simple as calling its constructor:
var request = new XMLHttpRequest();
This line creates an
XMLHttpRequest
object, which you can use to connect to, and request and
receive data from, a server.
using the xmlhttprequest object
Once you create the
XMLHttpRequest
object, you are ready to start requesting data with it. The first
step in this process is to call the
open()
method to initialize the object:
request.open(requestType, url, async);
This method accepts three arguments. The first,
requestType
, is a string value consisting of the
type of request to make. The value can be either
GET
or
POST
. The second argument is the URL to
send the request to, and the third is an optional
true
or
false
value indicating whether the request
should be made in asynchronous or synchronous mode.
Requests made in synchronous mode halt all JavaScript code from executing until a response is
received from the server. This can slow down your application's execution time. In most cases, you
want to use asynchronous mode, which lets the browser continue to execute your application's code