First step: create an instance
This is just a classical instance of class, but two options must be tried, for browser compatibility.
if (window.XMLHttpRequest) // Object of the current windows
{
xhr = new XMLHttpRequest(); // Firefox, Safari, ...
}
else
if (window.ActiveXObject) // ActiveX version
{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
}
Or exceptions may be used instead:
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Trying Internet Explorer
}
catch(e) // Failed
{
xhr = new XMLHttpRequest(); // Other browsers.
}
Second step: wait for the response
The response and further processing are included in a function and the return of the function will be assigned to the onreadystatechange attribute of the object previously created.
xhr.onreadystatechange = function() { // instructions to process the response };
if (xhr.readyState == 4)
{
// Received, OK
} else
{
// Wait...
}
Third step: make the request itself
Two methods of XMLHttpRequest are used:
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.
The request below read a document on the server.
xhr.open('GET', 'http://www.xul.fr/somefile.xml', true);
xhr.send(null);
No comments:
Post a Comment