JavaScript and AJAX
Transcription
JavaScript and AJAX
DOM JavaScript and AJAX DOM, JavaScript and AJAX Madalina Croitoru IUT Montpellier IUT Montpellier JavaScript • • • • Initially called LiveScript Initially called LiveScript Implemented in Netscape Navigator Microsoft adapts it in 1996: Jscript i f d i i 996 i European Computer Manufacturers Association (ECMA) standardizes it in 1997 JavaScript • Interpreted language Interpreted language • Host environment: – Web navigator, works by integrating JavaScript W b i t k b i t ti J S i t code in the XHTML documents using the <script> tag – Stand alone application (Adobe Creative Suite) – Part of operating systems (Dashboard – Part of operating systems (Dashboard Max OS X) Max OS X) JavaScript in navigators JavaScript in navigators • JavaScript JavaScript gives HTML designers a gives HTML designers a programming tool • JavaScript can put dynamic text into an HTML JavaScript can put dynamic text into an HTML page – JavaScript can react to events J S i t tt t – JavaScript can read and write HTML elements Datatypes • Number, Number, String, Boolean, Object, Null, String, Boolean, Object, Null, Undefined • Type conversion on the fly (to find out the Type conversion on the fly (to find out the type of an expression use typeof) • Value: NaN Value: NaN (Not A Number) (Not A Number) • Variable defined with var, if not any value provided then considered undefined provided then considered undefined – If var is not used then the variable is considered globat (to avoid!) Objects in JavaScript Objects in JavaScript • Everything Everything is an object in JavaScript is an object in JavaScript • Predefined: Global, Object, Function, Array, String Boolean Number Math Date String, Boolean, Number, Math, Date • Created with new • Classes extended (adding methods) done with prototype • To know the type of an object use the instanceof operator p JavaScript in a browser JavaScript in a browser • For For instance the access of the global object instance the access of the global object window: <script type= <script type=“application/javascript”> application/javascript > Var nav = window.navigator.userAgent; //browser information //browser information </script> Scripts in <head> Scripts in <head> <html> <head> <script type="text/javascript"> function message() { alert("This alert box was called with the onload event"); } </script> </head> <body onload <body onload="message()"> message() > </body> </html> Scripts in <body> Scripts in <body> <html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written by ( g y JavaScript"); </script> </body> / y </html> JavaScript Blocks of Code JavaScript Blocks of Code <script type="text/javascript"> p yp /j p { d document.write("<h1>This is t it (" h1 Thi i a heading</h1>"); h di /h1 ") document.write("<p>This document.write( <p>This is is a paragraph.</p> a paragraph.</p>"); ); document.write("<p>This is another paragraph.</p>"); } </script> </script> JavaScript dynamicity JavaScript dynamicity <script type="text/javascript"> //You will receive a different greeting based //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); theDay=d.getDay(); switch (theDay) h( h ) { case 5: document.write("Finally Friday"); break; case 6: case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break;; default: document.write("I'm looking forward to this weekend!"); } / p </script> JavaScript dynamicity‐ events JavaScript dynamicity • A mouse click ouse c c • A web page or an image loading: onLoad and onUnload • Mousing over a hot spot on the web page: onMouseOver and onMouseOut • Selecting an input field in an HTML form: onFocus, onBlur and onChange • Submitting an HTML form: onSubmit • A keystroke JavaScript dynamicity ‐ DOM JavaScript dynamicity • HTML DOM Properties: – – – – – – x.innerHTML ‐ the text value of x x.nodeName ‐ the name of x x.nodeValue ‐ the value of x x.parentNode ‐ the parent node of x x.childNodes ‐ the child nodes of x x.attributes ‐ the attributes nodes of x • HTML DOM Methods: – x.getElementById(id) ‐ get the element with a specified id – x.getElementsByTagName(name) x getElementsByTagName(name) ‐ get all elements all elements with a a specified tag name – x.appendChild(node) ‐ insert a child node to x – x.removeChild(node) x.removeChild(node) ‐ remove a child a child node from x innerHTML Property <html> <body> <p id="intro">Hello World!</p> <script type "text/javascript"> <script type="text/javascript"> txt=document.getElementById("intro").innerHTML; document.write("<p>The text from the intro paragraph: " + txt + "</p>"); </script> </body> </html> childNodes and nodeValue and nodeValue <html> <body> <p id="intro">Hello World!</p> <script type "text/javascript"> <script type="text/javascript"> txt=document.getElementById("intro").childNodes[0].nodeValue; document.write("<p>The text from the intro paragraph: " + txt + "</p>"); </script> </body> </html> HTML, JavaScript et PHP HTML, JavaScript et PHP 1. Le client utilise JavaScript pour prétraitements 2. Le client demande une page PHP 3. Le serveur exécute les « processing instructions » PHP et construit la réponse en HTML Utilisateur Poste client Serveur Web 4. Réponse contenant du HTML p q p et JavaScript qui sera affichée par le navigateur de l’utilisateur AJAX LLe client demande li t d d une page PHP Réponse contenant du HTML Réponse contenant du HTML et JavaScript Utilisateur Poste client JavaScript fait un appel JavaScript fait un appel non visible au serveur Le serveur répond en é d envoyant la donnée JavaScript met a jour p g la page en utilisant cette donnée Serveur Web AJAX • Asyncronous JavaScript and XML: JavaScript and XML: – Relies on a number of open technologies: • XHTML XHTML, CSS CSS • DOM model for the Web client, XML • Asynchronous data transfer using the XMLHttpRequest y g p q object • JavaScript based processing The XMLHttpRequest Object The XMLHttpRequest • Available Available on the web navigator via JavaScript on the web navigator via JavaScript • Allows to make a HTTP request (GET, POST) from a browser towards an application on a from a browser towards an application on a server in a (a) syncronous way: – Web pages do not need to be fully loaded because p g y their XHTML content (modelled in XML) can be manipulated using DOM xmlhttp=new XMLHttpRequest(); The XMLHttpRequest Object The XMLHttpRequest XMLHttpRequest object methods object methods • Ope Open(): opens a http connection with the server (): ope s a ttp co ect o t t e se e making a demand: GET, POST p p j _ xmlhttp.open("GET","ajax_info.txt",true); • Send(): transmits (a)synchronically data to the server xmlhttp.send(); • Abort(): stops current transfer • setRequestHeader(): specifies certain HTTP preferences (e.g. Content‐type) XMLHttpRequest object properties object properties • • • readyState: the code state of the tranfer (e.g. 4 is returned when the transfer is completed) transfer is completed) status: returns the HTTP code state of the server (e.g. 200 OK, 404 Not Found, etc.) y g – handling transfer events: g onreadystatechange xmlhttp.onreadystatechange=function() { if (xmlhttp readyState 4 && xmlhttp status 200) if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); Use of AJAX Use of AJAX • Periodic updates to a page (news) Periodic updates to a page (news) • Suggest, completion • Real time validation of user entered data Real time validation of user entered data • Existing libraries: E i ti lib i – Client level: Dojo, jQuery, Prototype, Rico, YUI etc. – Server level: HTML::AJAX (Php), Symphony (Php), S l l HTML AJAX (Ph ) S h (Ph ) jMaki (Java), DWR (Java), AJAX ASP.NET (C#) etc. – Specialised APIs: Google AJAX Libraries APIs: Google AJAX Libraries Mash ups Mash‐ups • Combining Combining, either at the client or at the server either at the client or at the server level, the content coming from several different sources offering new functionalities / different sources offering new functionalities / experiences