1 / 63

Ajax

Ajax. What is Ajax?. What is Ajax?. Ajax = Asynchronous JavaScript and XML. A group of interrelated Web development techniques used for creating interactive Web applications or Rich Internet applications. Rich u ser experience.

amanda
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. What is Ajax?

  3. What is Ajax? Ajax = Asynchronous JavaScript and XML A group of interrelated Web development techniques used for creating interactive Web applications or Rich Internet applications

  4. Rich user experience • Take a look at a typical desktop application(e.g. Spreadsheet) • The program responses intuitively and quickly • The program gives a user meaningful feedback'sinstantly • A cell in a spreadsheet changes color when you hover yourmouse over it • Icons light up as mouse hovers them • Things happen naturally • No need to click a button or a link to trigger an event

  5. Characteristics of conventional Web apps • “Click, wait, and refresh” user interaction • Page refreshes from the server needed for all events, datasubmissions, and navigation • Synchronous “request/response” communicationmodel • The user has to wait for the response • Page-driven: Workflow is based on pages • Page-navigation logic is determined by the server

  6. Issues of conventional Web apps • Interruption of user operation • Users cannot perform any operation while waiting for a response • Loss of operational context during refresh • Loss of information on the screen • Loss of scrolled position • No instant feedback's to user activities • A user has to wait for the next page • Constrained by HTML • Lack of useful widgets

  7. Rich Internet Applications • RIAs are Web applications that have the features and functionality of traditional desktop applications • The term was introduced in March 2002 by Macromedia (now merged into Adobe) • Traditional Web applications centred all activity around a client-server architecture with a thin client

  8. response request Thin client A thin client is a client computer or software which depends primarily on the central server for processing activities Internet Thin client Server

  9. Thin client systems • In thin client system, all processing is done on the server, and the client is only used to display static content • Drawback: all interaction with the application must pass through the server, which requires • data to be sent to the server • the server to respond • the page to be reloaded on the client with the response • “Click, wait, and refresh” user interaction

  10. Rich client Rich client is a client computer or software which typically provides rich functionality independently of the central server

  11. History of RIA technologies • Java Applet • Adobe Flash (Macromedia) • Java WebStart • DHTML • DHTML with Hidden IFrame • Ajax • . . .

  12. Java Applet • Pros: • Can use full Java APIs • Custom data streaming, graphic manipulation, threading, andadvanced GUIs • Well-established scheme • Cons: • Code downloading time could be significant • Use it if you are creating advanced UIs on theclientand downloading time is not a major concern

  13. Adobe Flash • Designed for playing interactive movies • Programmed with ActionScript • Implementation examples • Macromedia Flex • Laszlo suite (open source) • Pros: • Good for displaying vector graphics • Cons: • Browser needs a Flash plug-in • ActionScript is proprietary

  14. Adobe RIAs • The Adobe Flash Platform is the leading solution for building rich Internet applications, offering a complete set of integrated technologies supported by an established ecosystem http://www.adobe.com/resources/business/rich_internet_apps • Related technologies: • Adobe Creative Suite 4 • Adobe ColdFusion • Adobe LiveCycle ES • Adobe Scene7

  15. Java WebStart • Desktop application delivered over the net • Leverages the strengths of desktop apps and applet • Pros • Desktop experience once loaded • Leverages Java technology to its fullest extent • Disconnected operation is possible • Application can be digitally signed • Incremental redeployment • Cons • Old JRE-based system do not work • First-time download time could be still significant http://www.oracle.com/technetwork/java/javase/javawebstart/index.html

  16. DHTML (Dynamic HTML) DHTML = HTML + JavaScript + DOM + CSS • DHTML is NOT a language or a Web standard, it is a TERM used to describe the technologies used to make web pages dynamic and interactive • No asynchronous communication, however • Full page refresh still required • Reason why it has only a limited success

  17. DHTML with Hidden IFrame • IFrame (Inline Frame) was introduced in 1997 • More commonly used to insert content from another website into the current page • The embedded document can be changed without reloading the surrounding page • This makes many interactive applications possible - invisible IFrames can be used for asynchronous communication with the server • The visible user experience is uninterrupted – operationalcontext is not lost

  18. Ajax • DHTML plus asynchronous communicationcapability through XMLHttpRequestobject • Pros • Tremendous industry momentum • Many toolkits and frameworks are emerging • No need to download code & no plug-in required • Cons • Still browser incompatibility • JavaScript is hard to maintain and debug

  19. Ajax examples • Google Suggest • http://www.google.com/webhp?complete=1&hl=en • Google maps • http://maps.google.com/ • Gmail • http://gmail.com/

  20. Non-Ajax versus Ajax http://www.latvijaskarte.lv versus http://www.viss.lv/karte (powered by Google)

  21. Key aspects of Google Maps • A user can drag the entire map by using the mouse • Instead of clicking on a button or something • The action that triggers the download of new mapdata is not a specific click on a link but a moving themap around • Behind the scene - Ajax is used • The map data is requested and downloaded asynchronouslyin the background • Other parts of the page remains the same • No loss of operational context

  22. Usage cases for Ajax • Real-time server-side input form data validation • User IDs, serial numbers, postal codes • Removes the need to have validation logic at both client sidefor user responsiveness and at server side for security andother reasons • Auto-completion • Email address, name, or city name may be auto-completed asthe user types • Master detail operation • Based on a user selection, more detailed information can befetched and displayed

  23. Usage cases for Ajax • Advanced GUI widgets and controls • Controls such as tree controls, menus, and progress barsmay be provided that do not require page refreshes • Refreshing data • HTML pages may poll data from a server for up-to-date datasuch as scores, stock quotes, weather, or application-specificdata • Simulating server side notification • An HTML page may simulate a server-side notification bypolling the server in the background

  24. Ajax history • 1996: Internet Explorer introduced the IFrame element • 1998: Microsoft introduced Remote Scripting • 1999: Microsoft created the XMLHttpRequest object as an ActiveX control in Internet Explorer 5 • 2005: Jesse James Garrett have coined the term Ajax • 2006: the W3C released the first draft specification for the XMLHttpRequest object in an attempt to create an official web standard

  25. Jesse James Garrett

  26. Why Ajax? • Intuitive and natural user interaction • No clicking required • Mouse movement is a sufficient event trigger • "Partial screen update" replaces the "click, wait, andrefresh" user interaction model • Only user interface elements that contain new information areupdated (fast response) • The rest of the user interface remains displayed withoutinterruption (no loss of operational context) • Data-driven (as opposed to page-driven) • UI is handled in the client while the server provides data

  27. Why Ajax? • Asynchronous communication replaces"synchronous request/response model" • A user can continue to use the application while the clientprogram requests information from the server in thebackground • Separation of displaying from data fetching

  28. Non-Ajax interaction “Work-wait” pattern of user interaction in a classical web application

  29. Ajax interaction “Work-work” pattern of interaction in an Ajax application (asynchronous)

  30. Ajax web application model In the narrowest sense, Ajax issimply the business of making asynchronousrequests to the server

  31. Ajax application architecture Architecture of an N-tier web application, and the impact of Ajax on the design

  32. Technologies used inAjax • JavaScript • Loosely typed scripting language • JavaScript function is called when an event in a page occurs • Glue for the whole Ajax operation • DOM • API for accessing and manipulating structured documents • Represents the structure of XML and HTML documents • CSS • Allows for a clear separation of the presentation style from thecontent and may be changed programmatically by JavaScript • XMLHttpRequest • JavaScript object that performs asynchronous interaction with theserver

  33. XMLHttpRequest • JavaScript object • Adopted by modern browsers • Chrome, Firefox, Safari, Internet Explorer and Opera • Communicates with a server via standard HTTPGET/POST • XMLHttpRequest object works in the background forperforming asynchronous communication with thebackend server • Does not interrupt user operation

  34. Server-side Ajax request processing • Server programming model remains the same • It receives standard HTTP GETs/POSTs • Can use Servlet, JSP, JSF, ... • With minor constraints • More frequent and finer-grained requests from client • Response content type can be • text/xml • text/plain • text/json • text/javascript

  35. Steps of Ajax operation • A client event occurs • XMLHttpRequest object is created • XMLHttpRequest object is configured • XMLHttpRequest object makes an asynchronous request • Server component (e.g. Servlet) returns a text/XML documentcontaining the result • The XMLHttpRequest object calls the callback() functionand processes the result • The HTML DOM is updated

  36. Example 1 Real-time server-side input form data validation • Simple bank deposit form submission • Fields are going to be validated on the server on the fly

  37. Step 1: A client event occurs • A JavaScript function is called as the result of anevent • Example: validateAccount() JavaScript function ismapped as a event handler to a onkeyup event oninput form field whose id is set to “account” <input id="account" name="account" size="30" type="text" onkeyup="validateAccount();"/>

  38. Step 2: XMLHttpRequest object is created var req; function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateAccount() { initRequest(); req.onreadystatechange = processAccountRequest; var target = document.getElementById("account"); var url = "/servlet_jsp_demo/ajax_submit?account=" + escape(target.value); req.open("GET", url, true); req.send(null); }

  39. Step 3: XMLHttpRequest callback function var req; function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateAccount() { initRequest(); req.onreadystatechange = processAccountRequest; var target = document.getElementById("account"); var url = "/servlet_jsp_demo/ajax_submit?account=" + escape(target.value); req.open("GET", url, true); req.send(null); }

  40. Step 4:Asynchronous request var req; function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateAccount() { initRequest(); req.onreadystatechange = processAccountRequest; var target = document.getElementById("account"); var url = "/servlet_jsp_demo/ajax_submit?account=" + escape(target.value); req.open("GET", url, true); req.send(null); }

  41. Step 5: Server-side Servlet code public class AjaxFormServlet extends HttpServlet { private final List<String> accounts = Arrays.asList(new String[]{"111", "222", "333"}); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); String account = request.getParameter("account"); if (account != null && accounts.contains(account)) { response.getWriter().write("true"); } else { response.getWriter().write("false"); } } }

  42. Step 6: XMLHttpRequest calls callback function The XMLHttpRequest object was configured to call the processAccountRequest() function when there is a state change to the readyState of the XMLHttpRequest object function processAccountRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = req.responseText; setMessageUsingDOM("accountMessage", message); } } }

  43. Step 7: The HTML DOM is updated • JavaScript technology gets a reference to anyelement in a page using DOM API • The recommended way to gain a reference to anelement is to call • document.getElementById(“element_id"), where“element_id" is the ID attribute of an element appearing inthe HTML document • JavaScript technology may now be used to modifythe element's attributes; modify the element's styleproperties; or add, remove, or modify child elements

  44. Step 7: The HTML DOM is updated <p> <label for="account">Bankaccount:</label> <br> <input id="account" name="account" size="30" type="text" onkeyup="validateAccount();"/> <div id="accountMessage"></div> </p> • Adding <div>element for displaying a message

  45. Step 7: The HTML DOM is updated function setMessageUsingDOM(element, message) { var messageElement = document.getElementById(element); var messageText; if (message == "true") { messageElement.style.color = "green"; messageText = "Valid Account"; } else { messageElement.style.color = "red"; messageText = "Account is not recognized"; } var messageBody = document.createTextNode(messageText); if (messageElement.childNodes[0]) { messageElement.replaceChild(messageBody, messageElement.childNodes[0]); } else { messageElement.appendChild(messageBody); } }

  46. Result

  47. Some other JavaScript events onblur An element loses focus onchange The user changes the content of a field onclick Mouse clicks an object ondblclick Mouse double-clicks an object onfocus An element gets focus onkeydown A keyboard key is pressed onkeypress A keyboard key is pressed or held down onkeyup A keyboard key is released onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element

  48. XMLHttpRequest methods • open(“HTTP method”, “URL”, syn/asyn) • Assigns HTTP method, destination URL, mode • send(content) • Sends request including string or DOM object data • abort() • Terminates current request • getAllResponseHeaders() • Returns headers (labels + values) as a string • getResponseHeader(“header”) • Returns value of a given header • setRequestHeader(“label”, “value”) • Sets Request Headers before sending

  49. XMLHttpRequest properties • onreadystatechange • Set with an JavaScript event handler that fires at each statechange • readyState – current status of request • 0 = uninitialized • 1 = loading • 2 = loaded • 3 = interactive (some data has been returned) • 4 = complete • status • HTTP Status returned from server: 200 = OK

  50. XMLHttpRequest properties • responseText • String version of data returned from the server • responseXML • XML document of data returned from the server • statusText • Status text returned from server

More Related