DOM ja Ajax Jaana Holvikivi Metropolia
Sisältö Client - server communication Javascriptin käyttö DOM XMLHTTP pyyntö Ajaxin toiminta Esimerkkitapauksia
Sivujen haku HTTP:llä Selain: HTML, Skriptit, Plug-in Käyttäjän työasema HTTP request (pyyntö) HTTP: HTML sivut Internet Palvelin HTML pages Ohjelmapalvelin Tietokantapalvelin CGI ASP PHP Java SQL Oracle
HTTP requests GET /index.html HTTP/1.1 Host: www.evtek.fi Accept: www/source Accept: text/html Accept: image/gif User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-us; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3 a blank line * The client lists the Multipurpose Internet Mail Extension (MIME) types it will accept in return. Finally, the client sends a blank line indicating it has completed its request. 4
HTTP server response HTTP/1.1 200 OK Date: Mon, 09 Apr 2007 12:39:22 GMT Server: Apache/1.3.27 (Unix) (Red-Hat/Linux) Set-Cookie: fe_typo_user=4f74f6c85b; path=/; domain=www.evtek.fi Last-Modified: Wed, 08 Jan 2007 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=utf-8 5
GET and POST methods The difference between these two methods is in the way of sending data to the page: GET method sends data using URL (size limit), <form method="get" action="prog2.html"> http://www.google.com/search?sourceid=gmail&q=get%20method POST method sends data through a standard entrance <form method="post" action="http://www.school.fi/cgi-bin/postquery"> 6
Page requests: XMLHTTPRequest Ajax engine: Create server Request Send Monitor status Get response Process returned data XMLHTTPRequest (asynchronous) Returned data Server Application (PHP, Java, XSLT, ASP): Request readystate response Browser: Capture event/ Update page Database server User workstation SQL XML
Ajax rakennusosat Uudet selainohjelmat Javascript & libraries XMLHTTPRequest XHTML & CSS DOM XML Palvelinpuolen ohjelmat
Javascript, käyttö Javascript ladataan aina palvelimelta asiakkaalle Erillisenä tiedostona tai HTML-koodin sisällä Javascript suoritetaan asiakkaan selaimessa Palvelimen kuorma vähenee Toiminta nopeaa, esim. lomakkeen syötteen tarkistukset (numeric fields, dates, required fields) Javascript osaa käsitellä HTML sivun rakennetta (document); DOM
What do we get with Ajax? Interactivity in Web user interface Scrolling and zooming maps without Java applets Interaction on forms (automatic completion, checking of input, getting assistance, hints, tips) Update checking (mails) Customization of pages on-the -fly Imagination and creativity
Ajaxin käyttäjät http://www.google.com/webhp?complete=1 Google suggest Amazon: a9.com sivun sisältö muutettavissa; igoogle; itunes Yahoo!News Gmail Google Maps: tiles, dragging, zooming, push pins Facebook, Youtube, jne.
Javascript ja dokumentin rakenne
HTML dokumentti <html> <head> <title>this is a test page</title> </head> <body id="runko"> <p>alla on taulukko</p> <table> <tr> <td> solu </td> <td> cell </td> </tr> <tr> <td> <img src="kuva.gif"/> </td> <td> 1 </td> </tr> </table> </body> </html>
Sivun puurakenne <html> <head> <body> id <title> <p> <table> This is a test page Alla on taulukko <tr> <tr> <td> <td> <td> <td> data data data
Dokumenttipuu Document Root: html Element: Head Element: title Text: "test page" Element: table Element: tr Element: Body Element: p Text: "taulukko" Element: td Element: img Attribute: src
Document Object Model (DOM) Ohjelmointikielet osaavat käyttää sitä sivun osien käsittelyyn (php, java, c#, c++, Javascript ) Selaimet tulkitsevat sivurakenteen (Firefox, IE, Safari) XHTML -dokumentti rakentuu noodien muodostamaksi puuksi Ohjelmat osaavat navigoida puurakenteessa ja etsiä sieltä informaatiota Puurakenne vie paljon tilaa muistissa, eli suurten dokumenttien käsittely on tehotonta DOM mahdollistaa noodien lisäykset, poistot, siirrot, ja sisällön muuttamisen
DOM ja Javascript document.form1.text1.value <form name="form1"> <input type="text" name="text1"> </form> <a href="http://www.evtek.fi" onmouseover = "window.status='click here '; " > parent.location = word1 + word2 + ".html"
Dokumenttipuu: yleiset nimitykset Ancestor Parent / ancestor Node Sibling Attribute Child /descendant Namespace Descendant
Ominaisuudet (properties) x.innerhtml - elementin sisältö (teksti) x.nodename - nimi x.nodevalue - arvo x.parentnode - the parent node of x x.childnodes - the child nodes of x x.attributes - the attribute nodes of x
Puun prosessointi Aloitus juurisolmusta (root node; document-object) Metodit, joilla navigoidaan, esim. getelementbyid(id) getelementsbyname(nimi) getelementsbytagname(taginnimi) appendchild(node) - insert a child node to x removechild(node) - remove a child node from x
Yhteenveto: Ajax Javascript CSS XMLHttpRequest-object DOM Ajax (Asynchronous Javascript + XML) tarkoittaa uusien, kätevien tekniikoiden käyttöä asiakaspuolella XMLHttpRequest -object, kommunikoi palvelimen kanssa asynkronisesti ilman käyttäjän väliintuloa Ajax sisältyy selaimen toimintoihin! Ei tarvita erillisiä asennuksia (Java, tms.)
A Client request with AJAX Client request munsivu3.php Response contains HTML and Javascript To be displayed on the Browser window Server executes munsivu3.php And creates an HTML-reponse, That includes javascript user web client web server Javascript code sends a Server request invisibly Server responds by sending the data Javascript code updates the Web page with data The server can call the data base each time before responding
Ajax request Client requests an event handler e.g. onclick=startareq(); XMLHttpRequest-object is created on client Callback handler is registered Start of request httpreq.open( GET, stringa, true); Sending request httpreq.send(null); Server executes the request and returns data to the client Client takes either text or xml response httpreq.responsetext httpreq.responsexml
HTML Selain rakentaa sivun ja ohjaa toimintaa CSS JavaScript functions Browser: Capture event Browser: Update page XMLHTTPRequest Create Request Send Monitor status Returned data Get response Process returned data Server PHP script: Request readystate response Click button User workstation JavaScript functions
JSON: JavaScript Object Notation JSON is lightweight text-data interchange format JSON is language independent JSON is "self-describing" and easy to understand JSON uses JavaScript syntax for describing data objects { "employees": [ { "firstname":"john", "lastname":"doe" }, { "firstname":"anna", "lastname":"smith" }, { "firstname":"peter", "lastname":"jones" } ] } Name / value pairs arrays
JASON vs. XML Much Like XML JSON is plain text JSON is "selfdescribing" (human readable) JSON is hierarchical (values within values) JSON can be parsed by JavaScript JSON data can be transported using AJAX Much Unlike XML No end tag Shorter Quicker to read and write Can be parsed using built-in JavaScript eval() Uses arrays No reserved words