1 / 19

XMLHttpRequest Object and XML

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.

masao
Download Presentation

XMLHttpRequest Object and XML

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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)

  3. 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

  4. // 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

  5. 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) }

  6. XHR Object’s methods and properties

  7. 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.

  8. 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)

  9. 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.

  10. Handling Server Response • Async.html • Async.txt • async.js structure: • var xmlHttp = createXmlHttpRequestObject(); • function createXmlHttpRequestObject() • function process() • function handleRequestStateChange() • function handleServerResponse()

  11. 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>

  12. // 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

  13. 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()); } } }

  14. 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

  15. 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

  16. 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>

  17. Working with XML Structures • Books.js structure: • var xmlHttp = createXmlHttpRequestObject(); • function createXmlHttpRequestObject() • function process() • function handleRequestStateChange() • function handleServerResponse()

  18. Properties of DOM Elements Useful for Processing XML Documents

  19. // 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; }

More Related