1 / 43

AJAX

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?

hugh
Télécharger la présentation

AJAX

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

  2. Objectives • Understand and apply AJAX • Using AJAX in DOJO library

  3. Course Timetable • Duration: 180 minutes • Break: 15 minutes

  4. Prerequisites • HTML/DHTML • JavaScript • CSS • XML • Web Programming Basics

  5. Agenda • When we choose AJAX? • What is AJAX? • Why we choose AJAX? • How to apply AJAX? • Sample • AJAX in DOJO • Exercise

  6. When we choose Ajax? - Auto Completion Google - http://www.google.com.vn/

  7. When we choose Ajax? – Real-time validation

  8. When we choose Ajax? – Refreshing partial data

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

  10. Components: Traditional Web vs. AJAX

  11. User Interface: Traditional Web & AJAX

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

  13. How to apply Ajax? – Steps • Creating an instance • Sending a Request to the Server • Handle return results

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

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

  16. Sending a Request to the Server with GET var url = "sample.jsp"; var params = "param1=1&param2=2"; xmlRequest.open("GET", url +"?"+ params); xmlRequest.send(null);

  17. Sending a Request to the Server with POST var url = "sample.jsp"; var params = "param1=1&param2=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);

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

  19. XMLHttpRequest - readyState

  20. XMLHttpRequest - status code

  21. Example var url = "sample.jsp"; var params = "param1=1&param2=2";

  22. 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&param2=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; }

  23. Example – Server (Text format) • The file “sample.jsp” AJAX Training <%=request.getParameter("param1")%> <%=request.getParameter("param2")%>

  24. 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&param2=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; }

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

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

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

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

  29. DOJO – Directory Structure

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

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

  32. 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"));

  33. 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);

  34. AJAX - Http Get dojo.xhrGet({ url: "sample.jsp?param1=1&param2=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); } });

  35. AJAX - Http Post dojo.xhrPost({ url:"sample.jsp", content: { "param1":"1", "param2":2 }, load: function(data,ioargs){ dojo.byId("heading").innerHTML = data; } });

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

  37. AJAX - Get JSON (JavaScript Object Notation) object { foo: "bar", name: "SitePen", aFunction: function() { alert("internal function run"); }, nested: { sub: "element", another: "subelement" } }

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

  39. Ajax – XHR Arguments

  40. Demo & Exercise

  41. Questions & Answers

  42. Thanks for Your Attention

More Related