9. ajax & ria. 2 motto: o! call back yesterday, bid time return. — william shakespeare

22
9. AJAX & RIA

Post on 18-Dec-2015

213 views

Category:

Documents


1 download

TRANSCRIPT

9. AJAX & RIA

2

Motto:

O! call back yesterday, bid time return.—William Shakespeare

3

Concepts

Ajax Web Applications

Rich Internet Applications (RIAs) with Ajax

“Raw” Ajax with XMLHttpRequest Object

Ajax with XML, JSON and DOM

A Full-Scale Ajax-Enabled Application

Dojo Toolkit

4

Ajax Overview

• Usability of original web applications is bad– compared to desktop applications

• Rich Internet Applications (RIAs) – approximate the look, feel and usability of desktop applications– rich GUI– performance

• Ajax (Asynchronous JavaScript and XML)– client-side user interaction vs. server communication

• separate processes• parallel processing

– no page refreshes– asynchronous requests sent to the server via JavaScript – page updates via DOM modifications

5

Toolkits

• Ajax toolkits– “raw” Ajax is impractical– toolkits handle cross-browser portability problems

• Dojo• Prototype• Script.aculo.us

• RIA environments– rich, ready-to-use GUI – use Ajax toolkits

• JavaServer Faces• Adobe Flex• Microsoft Silverlight

6

Ajax Concept

• XMLHttpRequest object– manages interaction with the server – Commonly abbreviated as XHR

• Form of data passed between server and client – XML, or – JSON (JavaScript Object Notation)

• Client-side programming– XHTML– CSS– JavaScript

7

Traditional Web Application

• Traditional web application uses a synchronous model1. user fills in all the fields in a form and submits it2. browser generates a request, sends it to the server, and waits3. server receives the request, processes it, and sends back a

response page4. browser erases the original form page5. browser displays the new page

• Major usability problems1. the user can't interact with the browser while it waits for the

server's response2. the browser erases the old page before a new page appears

8

Traditional Synchronous Model

9

Ajax Application

• Ajax application uses an asynchronous model1. user fills in a field in a form that needs some feedback2. application creates an XMLHttpRequest object, uses it to send a

request to the server, and services the user without waiting3. server receives the request, processes it and sends back a response4. XMLHttpRequest receives the server's response and invokes a

callback function5. the callback function updates the original page without erasing it

• Advantages– application doesn't wait for the server's response– the user can interact with the page– callback function can update only a part of the page

10

Ajax Asynchronous Model

11

“Raw” Ajax with XMLHttpRequest

• To initiate an asynchronous request, the application– creates an instance of the XMLHttpRequest object– uses its open() method to set up the request

• if the third argument of open() is true the request is asynchronous– registers the callback function as the event handler for its onreadystatechange event

– uses its send() method to send the request to the browser• The callback function is called whenever the request

makes some progress• readyState property is progress indicator

– a value from 0 to 4– value 0: the request isn't initialized – value 4: the request is complete

• responseText property contains the response as text• responseXML property contains the response XML

12

Sample “Raw” Ajax Codevar request;

// Sets up and send an asynchronous request

function requestContent (url) {

try {

request = new XMLHttpRequest (); // create request object

request.onreadystatechange = stateChange; // register event handler

request.open ('GET', url, true); // set up the request

request.send (null); // send the request

} catch (exception) {

alert ("Request failed because of: " + exception);

}

}

// Displays the response data on the page

function stateChange () {

if (request.readyState == 4 && request.status == 200) {

document.getElementById ("content").innerHTML = request.responseText;

}

}

13

XMLHttpRequest PropertiesProperty Description

onreadystatechange Stores the callback function - the event handler that is called when the server responds

readyState

The request's progress. Usually used in the callback function to determine when the code that processes the response should be launched 0: the request is uninitialized; 1: the request is loading: 2 the request has been loaded; 3: data is being sent from the server: 4: the request has been completed

responseText Text that is returned to the client by the serverresponseXML If the server's response is in XML format, this property contains the XML

document, otherwise, it is empty. Can be used like a document object in JavaScript, which makes it useful for receiving complex data

statusHTTP status code of the requestStatus 200: request was successfulStatus 404: the requested resource was not foundStatus 500: there was an error while the server was processing the request

statusText Additional information on the request's status. Often used to display the error to the user when the request fails

14

XMLHttpRequest MethodsMethod Description

open

Initializes the request. Has two mandatory parameters - method and URL. The method parameter specifies the purpose of the request - typically GET if the request is to take data from the server or POST if the request will contain a body in addition to the headers. The URL parameter specifies the address of the file on the server that will generate the response. A third optional boolean parameter specifies whether the request is asynchronous - it's set to true by default

send Sends the request to the sever It has one optional parameter, data, which specifies the data to be POSTed to the server - it's s to null by default.

setRequestHeader Alters the header of the request. The two parameters specify the header and its new value. It is often used to set the content-type field.

getResponseHeaderReturns the header data that precedes the response body. It takes one parameter, the name of the head to retrieve. This call is often used to determine the response's type, to parse the response correctly.

getAllResponseHeaders Returns an array that contains all the headers that precede the response body.

abort Cancels the current request.

15

XMLHttpRequest Security

• XMLHttpRequest object can request resources only from the server that served the web application

• But there is a way out:– Implement a server-side proxy

1. proxy receives the request2. forwards it to the target server3. sends the target server's response to the web

application

16

JSON (JavaScript Object Notation)• JSON represents JavaScript objects as strings

– list of property names and values– comma-separated, enclosed in {}– name and value separated by :– values

• a string, a number, true, false , null• an object in JSON format• an array

– list of values– comma-separated, enclosed in []

17

JSON Advantages• Simpler alternative to XML

– easier to write– easier to parse– requires less space

• Used to pass data between the client and the server

• JSON can be easily converted into an JavaScript object – using eval()– but using a JSON parser is more secure

18

Dojo Toolkit

• JavaScript library for Ajax • Free• Open source• Asynchronous request in a single function call• Cross-browser functions that simplify partial

page/DOM updates• Event handling • Rich GUI widgets

19

Dojo Installation

1. Download the latest release– from www.Dojotoolkit.org/downloads

2. Extract the files from the archive file to web server

3. Include the Dojo.js file in your web application– place in the <head> of your XHTML document

<script type="text/javascript" src="path/Dojo.js">

where path is the path to the Dojo toolkit’s files

20

Dojo Packages

• Dojo is organized in packages

• dojo.require()– used to include specific Dojo packages

• dojo.io package – communication with the server

• dojo.events package – simplifies event handling

• dojo.widget package – rich GUI controls– To use a widget, set the dojoType attribute of any HTML

element• dojo.dom package

– DOM functions portable across many browsers

21

Dojo Request

• dojo.io.bind() – configures and sends asynchronous requests– takes an array of parameters, formatted as a JavaScript object– url parameter: the destination of the request– handler parameter: the callback function

– must have parameters type, data and event– mimetype parameter: the format of the response– load and error parameters: can replace handler parameter

– load function processes successful requests – error function processes unsuccessful requests

• handler function is called only when request completes• All the response data is sent to the callback function

22

Dojo Elements• dojo.dom.insertAtIndex()

– inserts an element into DOM• dojo.dom.removeNode()

– removes an element from the DOM• dojo.widget.byId()

– returns a Dojo widget• dojo.events.connect()

– links functions together• Dojo buttons use their own buttonClick event

– instead of the DOM's onClick event• Event object’s currentTarget property

– contains the element that initiated the event• dojo.date.toRfc3339()

– converts a date to yyyy-mm-dd format

• www.deitel.com/ResourceCenters/Programming/Dojo/tabid/2342/Default.aspx