Download presentation
Presentation is loading. Please wait.
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 1.Create an instance of the XMLHTTPRequest Object. 2.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 3.Deal with server’s response in the callback funtion 4.Go to step 2
4
Creating the XHR Object // 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.XMLHt tp"); } catch(e) { } } // return the created object or display an error message if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); else return xmlHttp; }
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.onreadystatechange –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 AJAX Foundations: Using XMLHttpRequest Hello, server!
12
Async.js // 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; }
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 element on the page myDiv = document.getElementById("myDivElement"); // display the status of the request if (xmlHttp.readyState == 1) { myDiv.innerHTML += "Request status: 1 (loading) "; } else if (xmlHttp.readyState == 2) { myDiv.innerHTML += "Request status: 2 (loaded) "; } else if (xmlHttp.readyState == 3) { myDiv.innerHTML += "Request status: 3 (interactive) "; } // when readyState is 4, we also read the server response
15
Async.js 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: "; 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); }
16
Working with XML Structures Building Reponsive Web Applications with AJAX and PHP 1-904811-82-5 Beginning PHP 5 and MySQL E-Commerce: From Novice to Professional 1-59059-392-8
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 + " "; // obtain a reference to the element on the page myDiv = document.getElementById("myDivElement"); // display the HTML output myDiv.innerHTML = "Server says: " + html; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.