190 likes | 322 Views
XMLHttpRequest Object and XML. What we should learn in this lesson What is the XHR object? How to create the XHR objects? XHR object properties XHR object status How to use XML in ajax programming? And roles of XML in ajax programming. Using the XMLHttpRequest Object.
E N D
XMLHttpRequest Object and XML • What we should learn in this lesson • What is the XHR object? • How to create the XHR objects? • XHR object properties • XHR object status • How to use XML in ajax programming? And roles of XML in ajax programming
Using the XMLHttpRequest Object • XMLHttpRequest (XMR) is the object that enables the JavaScript code to make asynchronous HTTP server requests • This functionality allows you to make HTTP requests, receive responses, and update parts of the page completely in the background, without the user experiencing any visual intereptions. • The XHR object was initially implemented by Microsoft in 1999 as an ActiveX object in IE • It become standard for all browsers now (except for IE6)
How to use XHR object • Create an instance of the XMLHTTPRequest Object. • Use the XHR object to make an asynchronous call to a server page, defining a callback function that will be executed automatically whenthe server response is received • Deal with server’s response in the callback funtion • Go to step 2
// creates an XMLHttpRequest instance function createXmlHttpRequestObject() { // will store the reference to the //XMLHttpRequest object var xmlHttp; // this should work for all browsers //except IE6 and older try { // try to create XMLHttpRequest object xmlHttp = new XMLHttpRequest(); } catch(e) { // assume IE6 or older try { xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); } catch(e) { } } // return the created object or display an error message if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); else return xmlHttp; } Creating the XHR Object
try/catch syntax try { // code that might generate an exception } catch (e) { // code that is executed only if an //exception was thrown by the try //block (exception details are //available through the e parameter) }
Open method • XMLHttpRequest.open(sMethod, sUrl [, bAsync] [, sUser] [, sPassword]) • sMethodRequired. String that specifies the HTTP method used to open the connection: such as GET, POST, or HEAD. This parameter is not case-sensitive. • sUrlRequired. String that specifies either the absolute or a relative URL of the XML data or server-side XML Web services. • bAsyncOptional. Variant that specifies true for asynchronous operation (the call returns immediately), or false otherwise. If true, assign a callback handler to the onreadystatechange property to determine when the call has completed. If not specified, the default is true. • sUserOptional. Variant that specifies the name of the user for authentication. If this parameter is null ("") or missing and the site requires authentication, the component displays a logon window. • sPasswordOptional. Variant that specifies the password for authentication. This parameter is ignored if the user parameter is null ("") or missing.
Initiating Server Requests Using XHR • Open method configures a request by setting various parameters and few optional ones • Enabling the AJAX mechanism by setting the onreadystatechange property with the callback method to be executed when the status of request changes • Send makes the request (accesses the server)
Handling Server Response • When making an asynchronous request, the execution of send doesn’t freeze until the server response is received, instead, the execution continues normally. • handleRequestStateChange method is the callback method that we set to handle request state change according to different stage of the redayState property.
Handling Server Response • Async.html • Async.txt • async.js structure: • var xmlHttp = createXmlHttpRequestObject(); • function createXmlHttpRequestObject() • function process() • function handleRequestStateChange() • function handleServerResponse()
File xhr.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>AJAX Foundations: Using XMLHttpRequest</title> <script type="text/javascript" src="async.js"></script> </head> <body onload="process()"> Hello, server! <br/> <div id="myDivElement" /> </body> </html>
// holds an instance of XMLHttpRequest var xmlHttp = createXmlHttpRequestObject(); // creates an XMLHttpRequest instance function createXmlHttpRequestObject() { // will store the reference to the XMLHttpRequest object var xmlHttp; // this should work for all browsers except IE6 and older try { // try to create XMLHttpRequest object xmlHttp = new XMLHttpRequest(); } catch(e) { // assume IE6 or older var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"); // try every prog id until one works for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) { try { // try to create XMLHttpRequest object xmlHttp = new ActiveXObject(XmlHttpVersions[i]); } catch (e) {} } } // return the created object or display an error message if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); else return xmlHttp; } Async.js
async.js // called to read a file from the server function process() { // only continue if xmlHttp isn't void if (xmlHttp) { // try to connect to the server try { // initiate reading the async.txt file from the server xmlHttp.open("GET", "async.txt", true); xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null); } // display the error in case of failure catch (e) { alert("Can't connect to server:\n" + e.toString()); } } }
Async.js // function that handles the HTTP response function handleRequestStateChange() { // obtain a reference to the <div> element on the page myDiv = document.getElementById("myDivElement"); // display the status of the request if (xmlHttp.readyState == 1) { myDiv.innerHTML += "Request status: 1 (loading) <br/>"; } else if (xmlHttp.readyState == 2) { myDiv.innerHTML += "Request status: 2 (loaded) <br/>"; } else if (xmlHttp.readyState == 3) { myDiv.innerHTML += "Request status: 3 (interactive) <br/>"; } // when readyState is 4, we also read the server response
else if (xmlHttp.readyState == 4) { // continue only if HTTP status is "OK" if (xmlHttp.status == 200) { try { // read the message from the server response = xmlHttp.responseText; // display the message myDiv.innerHTML += "Request status: 4 (complete). Server said: <br/>"; myDiv.innerHTML += response; } catch(e) { // display error message alert("Error reading the response: " + e.toString()); } } else { // display status message alert("There was a problem retrieving the data:\n" + xmlHttp.statusText); } } } Async.js
Working with XML Structures <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <response> <books> <book> <title> Building Reponsive Web Applications with AJAX and PHP </title> <isbn> 1-904811-82-5 </isbn> </book> <book> <title> Beginning PHP 5 and MySQL E-Commerce: From Novice to Professional </title> <isbn> 1-59059-392-8 </isbn> </book> </books> </response>
Working with XML Structures • Books.js structure: • var xmlHttp = createXmlHttpRequestObject(); • function createXmlHttpRequestObject() • function process() • function handleRequestStateChange() • function handleServerResponse()
Properties of DOM Elements Useful for Processing XML Documents
// handles the response received from the server function handleServerResponse() { // read the message from the server var xmlResponse = xmlHttp.responseXML; // obtain the XML's document element xmlRoot = xmlResponse.documentElement; // obtain arrays with book titles and ISBNs titleArray = xmlRoot.getElementsByTagName("title"); isbnArray = xmlRoot.getElementsByTagName("isbn"); // generate HTML output var html = ""; // iterate through the arrays and create an HTML structure for (var i=0; i<titleArray.length; i++) html += titleArray.item(i).firstChild.data + ", " + isbnArray.item(i).firstChild.data + "<br/>"; // obtain a reference to the <div> element on the page myDiv = document.getElementById("myDivElement"); // display the HTML output myDiv.innerHTML = "Server says: <br />" + html; }