AjaxThe hypeThe realityHow Ajax worksUnderlying technologiesStarting from the browser…The XMLHttpRequest objectGetting the XMLHttpRequest objectPreparing the XMLHttpRequest objectSending the XMLHttpRequest objectThe escape methodPutting it all togetherOn the server sideGetting the responseThe magic number 4The magic number 200Using response dataDisplaying the responseThe readyState propertySummaryProblem: Lost responseProblem: Only works the first timeProblem: JavaScript isn’t loadedBack to the HTML DOMAdding and removing event handlers<div> and <span> againinnerHTMLThe EndJan 14, 2019AjaxThe hypeAjax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XMLAjax is a technique for creating “better, faster, more responsive web applications”Web applications with Ajax are supposed to replace all our traditional desktop applicationsThese changes are so sweeping that the Ajax-enabled web is sometimes know as “Web 2.0”Ajax also cures cancer, ends hunger, and brings about world peaceThe realityAjax is a technique for creating “better, faster, more responsive web applications”But they still aren’t as responsive as desktop applications, and probably never will beWeb applications are useless when you aren’t on the webGUIs are HTML forms (and you know how beautiful and flexible those are)The technology has been available for some timeNevertheless, Ajax is the “hot new thing” because:Google uses it extensively, in things like Google Earth and Google SuggestIt has been given a catchy nameAjax is a useful technology, and a good thing to have on your resuméHow Ajax worksYou do something with an HTML form in your browserJavaScript on the HTML page sends an HTTP request to the serverThe server responds with a small amount of data, rather than a complete web pageJavaScript uses this data to modify the pageThis is faster because less data is transmitted and because the browser has less work to doUnderlying technologiesJavaScriptHTMLCSSXMLXML is often used for receiving data from the serverPlain text can also be used, so XML is optionalHTTPAll these are open standardsStarting from the browser…Your browser must allow JavaScript, or Ajax won’t workOtherwise, there’s nothing special required of the browserYour browser has some some way of providing data to the server—usually from an HTML formJavaScript has to handle events from the form, create an XMLHttpRequest object, and send it (via HTTP) to the serverNothing special is required of the server—every server can handle HTTP requestsDespite the name, the XMLHttpRequest object does not require XMLThe XMLHttpRequest objectJavaScript has to create an XMLHttpRequest objectFor historical reasons, there are three ways of doing thisFor most browsers, just dovar request = new XMLHttpRequest();For some versions of Internet Explorer, dovar request = new ActiveXObject("Microsoft.XMLHTTP");For other versions of Internet Explorer, dovar request = new ActiveXObject("Msxml2.XMLHTTP");Doing it incorrectly will cause an ExceptionThe next slide shows a JavaScript function for choosing the right way to create an XMLHttpRequest objectGetting the XMLHttpRequest objectvar request = null; // we want this to be globalfunction getXMLHttpRequest( ) { try { request = new XMLHttpRequest(); } catch(err1) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err2) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(err3) { request = null; } } } if (request == null) alert("Error creating request object!");}Preparing the XMLHttpRequest objectOnce you have an XMLHttpRequest object, you have to prepare it with the open methodrequest.open(method, URL, asynchronous)The method is usually 'GET' or 'POST'The URL is where you are sending the dataIf using a 'GET', append the data to the URLIf using a 'POST', add the data in a later stepIf asynchronous is true, the browser does not wait for a response (this is what you usually want)request.open(method, URL)As above, with asynchronous defaulting to trueSending the XMLHttpRequest objectOnce the XMLHttpRequest object has been prepared, you have to send itrequest.send(null);This is the version you use with a GET requestrequest.send(content);This is the version you use with a POST requestThe content has the same syntax as the suffix to a GET requestPOST requests are used less frequently than GET requestsFor POST, you must set the content type:request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');request.send('var1=' + value1 + '&var2=' + value2);The escape methodIn the previous slide we constructed our parameter list to the serverrequest.send('var1=' + value1 + '&var2=' + value2);This list will be appended to the URL (for a GET)However, some characters are not legal in a URLFor example, spaces should be replaced by %20The escape method does these replacements for yourequest.send('var1=' + escape(value1) + '&var2=' + escape(value2));Putting it all togetherHead:function getXMLHttpRequest () { ... } // from an earlier slidefunction sendRequest() { getXMLHttpRequest(); var url = some URL request.open("GET", url, true); // or POST request.onreadystatechange = handleTheResponse; request.send(null); // or send(content), if POSTfunction handleTheResponse() { if (request.readyState == 4) { if (request.status == 200) { var response = request.responseText; // do something with the response string } else { alert("Error! Request status is " + request.status); } }}Body: <input value="Click Me" type="button" onclick="sendRequest">On the server sideThe server gets a completely standard HTTP requestIn a servlet, this would go to a doGet or doPost methodThe response is a completely standard HTTP response, but……Instead of returning a complete HTML page as a response, the server returns an arbitrary text string (possibly XML, possibly something else)Getting the responseAjax uses asynchronous calls—you don’t wait for the responseInstead, you have to handle an eventrequest.onreadystatechange = someFunction;This is a function assignment, not a function callHence, there are no
View Full Document