1 / 46

Ajax

Ajax. AJAX. Asynchronous Javascript and XML La page n’est pas rechargée Rafraîchissement partiel La page web est traitée comme un template Asynchrone Le client peut continuer à interagir en attente de la réponse Utilisation

jera
Download Presentation

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. AJAX • Asynchronous Javascript and XML • La page n’est pas rechargée • Rafraîchissement partiel • La page web est traitée comme un template • Asynchrone • Le client peut continuer à interagir en attente de la réponse • Utilisation • Validation par le serveur des données d’un formulaire en temps réel • Auto-complétion • Préchargement à la demande. • Contrôles et effets sophistiquées dans les interfaces usager sans rechargement des pages • progress bar, calendriers, arbres… • Rafraîchissement des données et mode « push » par le serveur • Soumission partielle sans rechargement de la page: listes de formulaires dépendants. • Mashups • obtenir et intégrer des données provenant de plusieurs sources. • Page == application qui s’approche d’une application desktop.

  3. Technologies utilisées par Ajax • Cascading Style Sheets (CSS) • Un langage de balises pour définir le style de présentation d’une page, e.g. polices, couleurs.... • JavaScript • Élément clé : l’objet XMLHttpRequest utilisé pour échanger des données entre le client web et le serveur web • Document Object Model (DOM) • Fournit une vue logique de la page web sous forme d’arbre • XML • Format d’échange de données entre le serveur web et le client • D’autres formats peuvent aussi être utilisés • Par exemple, HTML, JavaScript Object Notation (JSON), ou texte simple.

  4. Fonctionnement

  5. Ajax et Javascript

  6. Les différents états d’une requête

  7. Les propriétés d’une requête XMLHttpRequest

  8. Les méthodes d’une requête XMLHttpRequest

  9. Construction et envoi d’une requête Post

  10. Ajax et Java

  11. Quelle stratégie de développement adopter ? •  Design Strategy 1: Do It Yourself  • Design Strategy 2: Use a Client-Side JavaScript Technology Library • Design Strategy 3: Use a Client-Server Framework  • Design Strategy 4: Do the Wrap Thing • Design Strategy 5: Go Remote • Design Strategy 6: Go All Java Technology

  12. Client Écrire soi-même le code en JavaScript, CSS, DOM, Présentation de la page. Serveur Coder explicitement la gestion de l’appel XMLHttpRequest Rendre une réponse appropriée Par exemple en XML Design Strategy 1: Do It Yourself

  13. Exemple • Implémenter une bulle pop-up

  14. Etapes à réaliser • Associer l’événement à une fonction JavaScript. • Créer et configurer un objet XMLHttpRequest. • Faire une requête au serveur à travers l’objet XMLHttpRequest. • Traiter la requête sur le serveur et rendre un document XML qui contient le résultat. • Traiter le résultat par la fonction JavaScript de callback(). • Mettre à jour le DOM représentant la page à l’aide des nouvelles données.

  15. Le code Javascript : popup.js // check if namespace object already exists, if not create itif(typeof(bpui) == 'undefined') { var bpui=new Object();}// create component namespace object // alone will contain the popup object bpui.alone=new Object(); /* time out variable When a user mouses over a book link in the catalog page, a timer begins counting. If the mouse is still hovering over the link after a timeout period of 1000 ms has elapsed, an XMLHttpRequest request is sent to the server. */ bpui.alone.timeout=""; // object to hold the request bpui.alone.req="";

  16. Fonction invoquée lorsque la souris est sur un lien // This is an exposed function to show and position the popup, and start the timer bpui.alone.showPopup=function(eventx, bookId) { // statically setup popup for simple case popupx="pop0"; // take into account window scrolling for accurate popup position var xx=0; var yy=0; if (!eventx) var eventx=window.event; if (eventx.pageX || eventx.pageY){ xx=eventx.pageX; // relatif au coin de la portion visible de la fenêtre yy=eventx.pageY; } else if (eventx.clientX || eventx.clientY) { xx=eventx.clientX + document.body.scrollLeft; // relatif au coin de la fenêtre yy=eventx.clientY + document.body.scrollTop; } document.getElementById(popupx).style.left= (xx + 3) + "px"; document.getElementById(popupx).style.top= (yy - 50) + "px"; //la fonction showPopupInternal sera invoquée à la fin du timeout bpui.alone.timeout=setTimeout("bpui.alone.showPopupInternal('" + popupx + "', '" + bookId + "')", 1000);}

  17. Déclenchement de la requête asynchrone // This function is called after initial timeout // that represents the delay bpui.alone.showPopupInternal=function(popupx, bookId) { // set up request (if not IE will not hit server) bpui.alone.req=bpui.alone.initRequest(); // url when using the jsp to serve the ajax request //url="../book_lookup.jsp?bookId=" + escape(bookId); // url when using the servlet to serve the ajax request url="../PopupServlet?bookId=" + escape(bookId); bpui.alone.req.onreadystatechange = bpui.alone.ajaxReturnFunction; bpui.alone.req.open("GET", url, true); bpui.alone.req.send(null); }

  18. Fonction de callback lorsque la réponse à la requête est reçue // call back function that is called once the AJAX call returns bpui.alone.ajaxReturnFunction=function() { // statically setup popup for simple case var componentId="pop0"; // check return of the call to make sure it is valid if (bpui.alone.req.readyState == 4) { // ready state is complete (readyState property equals 4) if (bpui.alone.req.status == 200) { // response is OK (status property equals 200) // get results and replace dom elements var resultx=bpui.alone.req.responseXML.getElementsByTagName("response")[0]; // and replace dom elements document.getElementById(componentId + "_title").innerHTML =resultx.getElementsByTagName("title")[0].childNodes[0].nodeValue; document.getElementById(componentId + "_message").innerHTML =resultx.getElementsByTagName("message")[0].childNodes[0].nodeValue;; // show popup with the newly populated information document.getElementById(componentId).style.visibility='visible‘; } else if (bpui.alone.req.status == 204){ alert("204 returned from AJAX call"); } } }

  19. La fonction bpui.alone.hidePopup() est invoquée sur l’événement « mouseout » pour cacher le ballon et réinitialiser le timeout // This is an exposed function to hide the popup and/or cancel to showing of the popup bpui.alone.hidePopup=function() { // statically setup popup for simple case popupx="pop0"; document.getElementById(popupx).style.visibility='hidden'; bpui.alone.clearTimeout(); } // This is an exposed function to clear the timer of the popup // in the mouseout event handler // if the showing of the popup is required bpui.alone.clearTimeout=function() { clearTimeout(bpui.alone.timeout); }

  20. Création de l’objet requête // setup request vehicle, need to do each time to make sure call is made to server. bpui.alone.initRequest=function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP");}}

  21. Le fichier css pour décrire l’apparence d’une bulle .bpui_alone_popMid{background: #FFFFFF; border-style: groove; border-width: thin; margin:0px 10px; width: 497px;} .bpui_alone_popTop{background:#696;margin:0px 10px; width: 500px; height:20px;z-index: 1;} .bpui_alone_popTop div.bpui_alone_cornerTL{width:100%;height:20px; background:url("./images/alone_corner_tl.gif") no-repeat top left} .bpui_alone_popTop div.bpui_alone_cornerTR{width:100%;height:20px; background:url("./images/alone_corner_tr.gif") no-repeat top right} .bpui_alone_popBot{background:#696;margin:0px 10px; width: 500px; height:10px;z-index: 1;} .bpui_alone_popBot div.bpui_alone_cornerBL{width:100%;height:10px; background:url("./images/alone_corner_bl.gif") no-repeat bottom left} .bpui_alone_popBot div.bpui_alone_cornerBR{width:100%;height:10px; background:url("./images/alone_corner_br.gif") no-repeat bottom right} div.bpui_alone_popup { position:absolute; left:0px; top:0px; z-index:2; visibility:hidden; }

  22. Dans la page html <a href="${url}" onmouseover="bpui.alone.showPopup(event, '${bookId}')" onmouseout="bpui.alone.hidePopup()"> <strong>${book.title}&nbsp;</strong> </a>

  23. Dans le fichier .jsp <!-- BEGIN: popup --> <script type="text/javascript" src="../popup.js"></script> <link type="text/css" rel="stylesheet" href="../popup.css" /> <!-- popup display div --> <div id="pop0" class="bpui_alone_popup"> <div class="bpui_alone_popTop"> <div class="bpui_alone_cornerTL"><div class="bpui_alone_cornerTR"> <center><font color="white"><b><span id="pop0_title">title</span></b></font></center> </div></div> </div> <div class="bpui_alone_popMid"> <table border="0" style="width: 100%"> <tr> <td> <table border="0" bgcolor="#ffffff" cellpadding="5" cellspacing="5"> <tr> <td><span id="pop0_message">Value</span></td> </tr> </table> </td> </tr> </table> </div> <div class="bpui_alone_popBot"> <div class="bpui_alone_cornerBL"><div class="bpui_alone_cornerBR"> </div></div> </div> </div> <!-- END: popup -->

  24. Ecrire le servlet public class PopupServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }

  25. Ecrire le servlet public class PopupServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=UTF-8"); PrintWriter out = response.getWriter(); BookstoreMessages messages=new BookstoreMessages(); String bookId=request.getParameter("bookId"); try { out.println("<response>"); if(bookId != null) { BookDBAO bookDBAO=(BookDBAO)getServletContext().getAttribute("bookDBAO"); Book book=bookDBAO.getBook(bookId); out.println("<title><![CDATA[Book Detail]]></title>"); out.println("<message><![CDATA["); out.println("<b>" + book.getTitle() + "</b><br/>"); // etc. } } catch(Exception ee) { ee.printStackTrace(); } finally { out.println("</response>"); out.flush(); out.close(); } }

  26. Do it yourself : avantages et inconvénients • Avantages • Offers fine-grained control over Ajax processing • Inconvénients • Requires a lot of Ajax-related coding • Requires knowledge of multiple languages and technologies • Requires developers to contend with browser incompatibilities • Requires developers to contend with UI issues • Bookmark d’une page Ajax : que faut-il garder car l’URL est la même • Can be difficult to debug. • Exposes JavaScript technology code -- a potential security risk

  27. Design Strategy 2: Use a Client-Side JavaScript Technology Library • Utiliser des librairies qui fournissent des fonctionnalités Ajax • Dojo toolkit, Prototype, Script.aculo.us, Rico. • La libraire dojo.io permet d’abstraire les opération de communication Ajax avec le serveur • Cache les détails de bas niveau des opérations XMLHttpRequest. • Prototype • Framework permettant d’abstraire XMLHttpRequest, de manipuler le DOM • Script.aculo.us, Rico construit au-dessus de Prototype • Ajax, drag and drop, effets UI, etc.

  28. Use a Client-Side JavaScript Technology Library: avantages et inconvénients • Avantages • Hides low-level Ajax "plumbing" • Reduces the need for JavaScript technology coding • Handles browser incompatibilities in processing Ajax • Handles some common Ajax issues such as bookmarking and support for the Back button. • Established user communities for these toolkits can help in answering questions • Inconvénients • Requires some knowledge of JavaScript technology • Might need to mix and match JavaScript technology libraries • Might not meet all Ajax needs

  29. Design Strategy 3: Use a Client-Server Framework • JavaServer Faces technology frameworks • Java EE 5 SDK, ICEfaces, Ajax4jsf, and Project Dynamic Faces. • Direct Web Remoting (DWR), • Design Strategy 5: Go Remote • Google Web Toolkit (GWT) • Design Strategy 6: Go All Java Technology

  30. JavaServer Faces (JSF) • designed to simplify building functionally rich UIs for web applications. • component model. • a set of APIs for • representing UI components and for managing their state • programmatically handling events on components, as well as converting and validating input data • Les composantes s’exécutent sur le serveur et sont « rendues » sur le client • enables application developers to build Ajax into a web application by dragging and dropping visual components. • extensible

  31. To use an Ajax-enabled component on a page • reference the custom component's tag library, • specify the tag for the component, • and map a pertinent event to a JavaScript technology function that handles the event.

  32. La fonction de lancement de la requête

  33. La fonction « callback »

  34. Use a Client-Server Framework : avantages et inconvénients • Avantages • Page authors do not need to know all of JavaScript technology, CSS, and DOM. • Ajax-enabled custom components are reusable. • Component developers can take advantage of JavaServer Faces technology features • Application developers can add Ajax to a web application by dragging and dropping visual components • Inconvénients • Has many of the same disadvantages as the do-it-yourself approach

  35. Design Strategy 4: Do the Wrap Thing • Combining • client-side JavaScript technology libraries • client-server frameworks • jMaki • a framework for wrapping JavaScript technology widgets in JSP tags or JavaServer Faces components.

  36. Utilisation de jMAKI • includes a jMaki widget on a page in the same way as a JSP tag or JavaServer Faces component • Définir un widget jMAKI • an HTML template file that specifies the page layout for the widget, • a CSS file that specifies the style parameters for the widget, • a JavaScript technology file that specifies the widget's behavior.

  37. Pros and Cons of Using jMaki • Pros • Hides the JavaScript technology details • jMaki makes widgets available as JSP tags or as JavaServer Faces components • Integrated into the Project Phobos scripting framework • creating a framework for building web applications using scripting languages. • allowing to use the Java programming language rather than a scripting language, when appropriate, to perform a task • Cons • Requires some knowledge of JavaScript

  38. Design Strategy 5: Go Remote • frameworks • Direct Web Remoting (DWR) • JSON-RPC. • enable developers to build Ajax into an application through Remote Procedure Call (RPC)-like calls in JavaScript technology code • Server side • create a simple Java class to handle the Ajax requests for the pop-up balloon content. • the class Popup and the method in the class that provides the book details for the pop-up balloon getDetails. • client-side • JavaScript technology function that is triggered in response to the appropriate mouseover event. • write the callback function in the client JavaScript technology code

  39. The DWR framework • handle the low-level details • creating, configuring, and performing operations on an XMLHttpRequest object. • generates the equivalent of a Remote Method Invocation (RMI) stub on the client for the class. • That stub is a JavaScript technology class that includes the low-level XMLHttpRequest operations. • marshals the data exchanged between the generated JavaScript technology class and the server. • converting parameters that the client-side JavaScript technology passes, • converting the values that the server-side Java technology returns. • creates on the server a servlet • called DWRServlet • receives the request and dispatches it to the Popup class for processing.

  40. Go Remote : avantages et inconvénients • Avantages • Hides low-level Ajax "plumbing". • Allows Java application developers to make Ajax requests using a familiar syntax • Allows developers to expose existing business logic to an Ajax client with minimum effort • Provides security controls • DWR offers various controls to protect remote classes and methods from unwarranted exposure • Inconvénients • Requires knowledge of JavaScript. • Only works with Java objects

  41. Design Strategy 6: Go All Java Technology • Google Web Toolkit (GWT). • allows developers to build Ajax-enabled applications exclusively in the Java programming language • client side • a GWT Java-to-JavaScript technology compiler converts the Java programming language code on the client to JavaScript technology code and HTML. • server-side • Java technologies such as servlets, JSP technology, and JavaServer Faces technology. • Building a UI for an Ajax-enabled application using GWT • GWT provides a library of commonly used widgets • JFC/Swing paradigm continues in GWT's event model. • Testing and debugging • a "hosted mode". • runs your client in a Java virtual machine*. • GWT provides a browser and a simple servlet so that you can do a test run of the application. • set breakpoints that hook back into your Java code. • a "web mode" where you can run the compiled version of the application • that is, the version that contains the JavaScript technology code and HTML.

  42. Go All Java Technology : avantages et inconvénients • Avantages • Allows developers to build Ajax-enabled applications in the Java programming language. • Developers do not need to know JavaScript technology, CSS, or DOM. • Provides GWT hosted mode, an environment that enables debugging. • Handles browser incompatibilities in processing Ajax. • Developed and supported by Google. • Inconvénients • Generated JavaScript technology code has its drawbacks • you might sometimes need to examine the generated JavaScript technology code

  43. iFrame • inline frame • Un élément html qui permet d’imbriquer un autre document html à l’intérieur du document principal.

  44. Références • Ajax Design Strategies • http://java.sun.com/developer/technicalArticles/J2EE/AJAX/DesignStrategies/ • Creating an AJAX-Enabled Application, a Do-It-Yourself Approach • http://java.sun.com/developer/technicalArticles/J2EE/hands-on/legacyAJAX/do-it-yourself/index.html • Survey of Ajax/JavaScript Libraries. • http://chandlerproject.org/bin/view/Projects/AjaxLibraries • Google web toolkit • http://code.google.com/webtoolkit/

More Related