18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

HTTP Requests<br />

In many modern browsers, it’s possible to initiate HTTP requests directly from <strong>JavaScript</strong> and get the<br />

result back in <strong>JavaScript</strong>, completely eliminating the need for hidden frames and other such trickery.<br />

At the center of this exciting new capability is an object Microsoft created called the XML HTTP request.<br />

This object came along with MSXML but wasn’t fully explored until recently. Essentially, an XML HTTP<br />

request is a regular HTTP request with added functionality for sending and receiving XML code.<br />

To create a new XML HTTP request in Internet Explorer, you must once again use an ActiveXObject:<br />

var oRequest = new ActiveXObject(“Microsoft.XMLHTTP”);<br />

Like the XML DOM in IE, the XML HTTP request object has multiple versions, so a function is necessary<br />

to make sure you’re using the most recent one:<br />

function createXMLHTTP() {<br />

var arrSignatures = [“MSXML2.XMLHTTP.5.0”, “MSXML2.XMLHTTP.4.0”,<br />

“MSXML2.XMLHTTP.3.0”, “MSXML2.XMLHTTP”,<br />

“Microsoft.XMLHTTP”];<br />

for (var i=0; i < arrSignatures.length; i++) {<br />

try {<br />

var oRequest = new ActiveXObject(arrSignatures[i]);<br />

return oRequest;<br />

Client-Server Communication<br />

}<br />

} catch (oError) {<br />

//ignore<br />

}<br />

}<br />

throw new Error(“MSXML is not installed on your system.”);<br />

After you have created it, you can use the open() method to specify the request to send. This method<br />

takes three arguments: the type of request to send (GET, POST, or any other HTTP method supported by<br />

the server); the URL of the request; and a Boolean indicating whether the request should be sent asynchronously<br />

or not (the same as you do with the XML DOM load() method). <strong>For</strong> example:<br />

oRequest.open(“get”, “example.txt”, false);<br />

After opening the request, you must send it by using the send() method. This method always requires<br />

an argument, which can be null most of the time:<br />

oRequest.send(null);<br />

If you choose to make the request synchronously (setting the third argument to false), the <strong>JavaScript</strong><br />

interpreter waits for the request to return. When the response comes back, it fills the status property<br />

493

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!