440 likes | 753 Views
AJAX. Objectives. Understand and apply AJAX Using AJAX in DOJO library. Course Timetable. Duration: 180 minutes Break: 15 minutes. Prerequisites. HTML/DHTML JavaScript CSS XML Web Programming Basics. Agenda. When we choose AJAX? What is AJAX? Why we choose AJAX? How to apply AJAX?
E N D
Objectives • Understand and apply AJAX • Using AJAX in DOJO library
Course Timetable • Duration: 180 minutes • Break: 15 minutes
Prerequisites • HTML/DHTML • JavaScript • CSS • XML • Web Programming Basics
Agenda • When we choose AJAX? • What is AJAX? • Why we choose AJAX? • How to apply AJAX? • Sample • AJAX in DOJO • Exercise
When we choose Ajax? - Auto Completion Google - http://www.google.com.vn/
What is Ajax? • AJAX = Asynchronous JavaScript and XML • Ajax is not new programming language, but a new way to use existing standards. • Using JavaScript object XmlHttpRequest to communicate asynchronously with a server-side component
Why we choose Ajax? • Pros • Creating better, faster, and more interactive web applications • JavaScript can communicate directly with the server without reloading the page • Web pages request small bits of information from the server instead of whole pages • Cons • Breaks back button functionality • Javascript can be turned off in browser
How to apply Ajax? – Steps • Creating an instance • Sending a Request to the Server • Handle return results
XMLHttpRequest - Creating an instance function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } } } } return this.req; }
XMLHttpRequest – Sending a request to server • xmlHttp.open(method, url); • Method: The most commonly used methods are GET and POST • URL: This parameter identifies the page being requested • xmlHttp.send(params); • The send method takes one parameter, which is used for POST data. When the request is a simple GET that doesn’t pass any data to the server, like our current request, we set this parameter to null.
Sending a Request to the Server with GET var url = "sample.jsp"; var params = "param1=1¶m2=2"; xmlRequest.open("GET", url +"?"+ params); xmlRequest.send(null);
Sending a Request to the Server with POST var url = "sample.jsp"; var params = "param1=1¶m2=2"; xmlRequest.open("POST", url); // Send the proper header information along with the request xmlRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlRequest.send(params);
XMLHttpRequest - Handle return results • responseText (html format “text/html”) • responseXml (xml format “text/xml”) xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response if (xmlRequest.getResponseHeader("Content-type").indexOf("text/xml") >= 0) { alert(xmlRequest.responseXML); } else { alert(xmlRequest.responseText); } } }
Example var url = "sample.jsp"; var params = "param1=1¶m2=2";
Example – Client (Text format) // When the user clicking on the Hello World !!! button function hello() { // Create XMLHttpRequest instance var xmlRequest = getXMLHttpRequest(); // Send the request to the server using GET method var url = "sample.jsp"; var params = "param1=1¶m2=2"; xmlRequest.open("GET", url + "?" + params); xmlRequest.send(null); // Register the event to process data xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response alert(xmlRequest.responseText); } } } </script> </head> <body> <h1>Hello World</h1> <input type="button" onclick="hello()" value="Hello World !!!"/> </body> </html> <html> <head> <title>AJAX Hello World</title> <script type="text/javascript"> function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = newXMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = newActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = newActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } } } } returnthis.req; }
Example – Server (Text format) • The file “sample.jsp” AJAX Training <%=request.getParameter("param1")%> <%=request.getParameter("param2")%>
Example – Client (XML format) // When the user clicking on the Hello World !!! button function hello() { // Create XMLHttpRequest instance var xmlRequest = getXMLHttpRequest(); // Send the request to the server using GET method var url = "sampleXML.jsp"; var params = "param1=1¶m2=2"; xmlRequest.open("GET", url + "?" + params); xmlRequest.send(null); // Register the event to process data xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response varxml = xmlRequest.responseXML; vartitle = xml.getElementsByTagName("title") .item(0).firstChild.nodeValue; alert(title); } } } </script> </head> <body> <h1>Hello World</h1> <input type="button" onclick="hello()" value="Hello World !!!"/> </body></html> <html> <head> <title>AJAX Hello World</title> <script type="text/javascript"> function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = newXMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = newActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = newActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } } } } returnthis.req; }
Example – Server (XML format) • The file “sampleXML.jsp” <%@ page import="java.io.PrintWriter" %> <% response.setContentType("text/xml"); PrintWriter output = response.getWriter(); try { output.write("<?xml version=\"1.0\"?>"); output.write("<title>"); output.write("AJAX Training " + request.getParameter("param1") + " " + request.getParameter("param2")); output.write("</title>"); output.close(); } catch (Exception e) { e.printStackTrace(); } %>
Exercise • Using POST method • Replace the “Hello World” text by exactly the text retrieved from the server • The server returns the html format with the given color parameter to display the text “AJAX Training <param1> <param2>”
AJAX in DOJO • DOJO • Introduction • Directory Structure • Basic Template • Logging & Debugging • Dom & Event • AJAX • Http Get • Http Post • Submit Form • Get Json Object • XHR Arguments
DOJO - Introduction • DOJO is an Open Source DHTML toolkit written in JavaScript. • DOJO supplies a solid set of tools for DOM manipulation, Animations, Ajax, Event and keyboard normalization, Internationalization (i18n) and Accessibility (a11y) … • Main site: http://dojotoolkit.org/
DOJO - Basic Template <html> <head> <title>Dojo Toolkit Test Page</title> <!-- load the dojo toolkit base --> <script type="text/javascript" src="js/dojo/dojo.js" djConfig="parseOnLoad:true, isDebug:true"></script> <script type="text/javascript"> /* our JavaScript will go here */ </script> <style type="text/css"> /* our CSS can go here */ </style> </head> <body> </body> </html>
DOJO - Logging & Debugging <script type="text/javascript"> console.log("Nothing happening"); console.debug("Checking to make sure nothing happened"); console.info("Something might happen."); console.warn("Something happened, but it's no big deal."); console.error("Cough cough!"); </script>
DOJO - DOM & Event • DOM Ready dojo.addOnLoad dojo.addOnLoad(function() { console.log("The document is ready"); }); • Selecting DOM Nodes with dojo.query & dojo.byId // Query by tag. Equivalent to document.getElementsByTagName("img"); console.dir(dojo.query("img")); // Query by class. console.dir(dojo.query(".offToSeeTheWij")); // Query by id. Equivalent to document.getElementById("widget123"); console.dir(dojo.query("#widget123")); console.dir(dojo.byId("widget123")); // Select just image tags with the class offToSeeTheWijconsole.dir(dojo.query("img.offToSeeTheWij"));
DOJO - DOM & Event … • Chain of Effects dojo.query("#heading") // add "testClass" to its class="" attribute .addClass("testClass") // set background color .style("backgroundColor","gray"); • Event Handlers dojo.query(".deadLink").onclick(function(evt) { console.log('Clicking'); }); dojo.connect(dojo.byId("mainForm"), "onsubmit", formSubmit);
AJAX - Http Get dojo.xhrGet({ url: "sample.jsp?param1=1¶m2=2", handleAs: "text", load: function(data,args) { dojo.byId("heading").innerHTML = data; }, // if any error occurs, it goes here: error: function(error,args) { console.warn("error!",error); } });
AJAX - Http Post dojo.xhrPost({ url:"sample.jsp", content: { "param1":"1", "param2":2 }, load: function(data,ioargs){ dojo.byId("heading").innerHTML = data; } });
AJAX - Submit Form <script type="text/javascript"> var formSubmit = function(e) { e.preventDefault(); // prevent the form from actually submitting dojo.xhrPost({// submit the form in the background url: "sample.jsp", form: "mainForm", handleAs: "text", load: function (data, ioargs) { dojo.byId("heading").innerHTML = data; } }); }; dojo.addOnLoad(function() { var theForm = dojo.byId("mainForm"); dojo.connect(theForm,"onsubmit",formSubmit); }); </script> <form id="mainForm"> <input type="hidden" name="param1" value="1"/> <input type="hidden" name="param2" value="2"/> <input type="submit" value="test"/> </form>
AJAX - Get JSON (JavaScript Object Notation) object { foo: "bar", name: "SitePen", aFunction: function() { alert("internal function run"); }, nested: { sub: "element", another: "subelement" } }
AJAX - Get JSON object … <script type="text/javascript"> var postData = function(){ dojo.xhrPost({ url: "sample.json", handleAs: "json", load: function (data,ioargs){ // success: set heading, run function dojo.byId("heading").innerHTML += " by: "+data.name; if (data.aFunction && data.aFunction()) { // we just ran data.aFunction(). should alert() ... } } }); }; dojo.addOnLoad(postData); </script>