Vous êtes sur la page 1sur 49

Introduction to AJAX

Chapter 10 (Text Book)

Learning Outcomes
By the end of this module, you will learn:
What is Ajax? How to create a simple Ajax application Document types used by Ajax JSON

OVERVIEW OF AJAX

Overview of Ajax
Ajax aims to provide more responsive web applications Goal of Ajax is to provide Web-based applications with responsiveness approaching that of desk-top applications In normal request/response HTTP cycles, the browser locks waiting for the response and an entire page must be displayed. One of the key principles of Web 2.0 is using the Web as a platform for application development -instead of merely Web pages With Ajax, asynchronous requests may be made and responses are used to update part of a page.

Synchronous Communication

Synchronous: user must wait while new pages load the typical Communication pattern used in web pages (click, wait, refresh)
4

Asynchronous Communication
Client

Ajax

Asynchronous: user can keep interacting with page while data loads Communication pattern made possible by Ajax
5

What is Ajax?
Asynchronous JavaScript and XML
term coined in 2005 by Jesse James Garrett

Ajax is group of interrelated development techniques used for creating interactive web applications

Not a programming language; a way of using JS


Ajax does not use any new programming languages or markup languages
Client side: JavaScript, XML, XHTML, DOM, CSS
Server side: any (PHP, servlets, ASP.NET, etc.)

It allows web applications to retrieve data from the server

asynchronously

What is Ajax? (Cont.)


There have been developments in the technologies used in Ajax apps since Garretts original article JavaScript is not the only client-side scripting language that can be used

Other languages such as VBScript are capable of the required functionality


The XMLHttpRequest object is not necessary for asynchronous communication XML is not required for data interchange - and therefore XSLT is not required for the data manipulation

JavaScript Object Notation (JSON) is often used as an alternative format


for data interchange other formats such as preformatted HTML or plain text can also be used
7

Approaches to Ajax
The iframe element can be hidden and it allows

asynchronous requests to a server


Javascript support allows updating other elements of the page
from the frame response

Microsoft introduced the XmlDocument and XMLHTML objects which are used to make asynchronous requests

directly from JavaScript


Most browsers now name the object XMLHttpRequest
8

Uses of Ajax
AJAX has many potential
uses including: - updating page information - real-time data validation - responding to server events - real-time interaction - auto completion
- Google Suggest helped to initially popularise Ajax in 2005

Advantages of Ajax

User can continue to interact with a page while the request is in progress

Less data needs to be transmitted (reduces bandwidth usage / load time)


Page update is quicker because only a part of a page is modified.

10

Disadvantages of Ajax

Dynamically created pages do not register themselves in a browser's history


BACK button does not return the user to an earlier state of an Ajaxenabled page But to the last page visited

Dynamic web page updates make it difficult for a user to bookmark a particular state of an application Any browser or device which does not support Ajax or JavaScript, will not be able to use its functionality. Because most web crawlers dont execute JavaScript code, search engines cannot index Ajax-retrieved content

Thus web applications need to provide an alternative means of accessing such content

11

A typical Ajax Request

12

XMLHTTPREQUEST

13

XMLHttpRequest

XMLHttpRequest (XHR)

The core JavaScript object that makes Ajax possible an API that can be used by JavaScript and other web browser scripting languages used to transfer XML and other text data between a web server and a browser

Though it can do synchronous fetches, it is almost always asynchronous Examples of web apps that make use of XMLHttpRequest include:

Google Maps
Windows Live's Virtual Earth

Facebook

14

Creating the XMLHttpRequest object


function basicAjaxExample() { var xmlHttp; try { xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari

} catch (e) {
try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; // IE 5.5+

// IE 6.0+

}
} }

15

XMLHttpRequest object methods

open() and send()


these methods are used to send requests to the server


open() takes three arguments:

the method to use when sending the request (GET or POST) the URL of the server-side script whether or not the request should be handled asynchronously

send() method the request off to the server

if using GET and all the data is in the URL, send has null as its argument if using post, send would take a variable or string containing the data being passed back

16

XMLHttpRequest object methods

The onreadystatechange Property

After a request is sent to the server, need a function to receive the data returned The onreadystatechange property stores a function to process the response from the server

the function is stored in the property (to be called automatically when needed)

The following code sets the onreadystatechange property and stores an empty function inside it:
xmlHttp.onreadystatechange=function() { // code will go here }

17

Properties of the XMLHttpRequest object


The readyState Property
The readyState property holds the status of the server's response
Every time the readyState changes, the onreadystatechange function is executed

Possible values for the readyState property:


State 0 1 Description Request not initialized Request not set up

2 3
4
18

Request sent Request in process


Request complete

Properties of the XMLHttpRequest object


The data sent back from the server can be retrieved with one of the following :
The responseText Property use this if you dont want to process that data in Javascript and you just want to display it (e.g. HTML) The responseXML Property
gives you a DOM object of the XML returned.

19

Asynchronous XMLHttpRequest Template


functionMyEventHandler () { varxhr = new XMLHttpRequest(); xhr.onreadystatechange= function() { if (xhr.readyState== 4 &&xhr.status== 200) { do something with xhr.responseText; } } xhr.open("get", url, true); xhr.send(null); }
20

Live Demo

21

DOCUMENT TYPES

22

Return Document Forms


Plain text XHTML XML JSON
Unstructured data

structured data

23

XHTML
Original XHTML document: <div id=result> no result available </div> To update this element with returned data,
var dom= document.getElementById(result); dom.InnerHTML=xhr.responseText

Disadvantages:
Its not easy to extract data written in XHTML format.
24

XML
Returned result can be parsed using DOM Disadvantages:
XML is tedious to parse and use Support for DOM parsing methods varies among browsers.

25

JavaScript Object Notation (JSON)


A lightweight computer data-interchange format. JSON is a subset of JavaScript. JSON can be parsed by a JavaScript parser, as well as other programming languages It is both human readable and machine readable

26

JSON

27

Data Types (Values)


There are only six kinds of data in JSON:
Strings Numbers Booleans
Objects Arrays
value string number object array
true false

null

null

Strings
Sequence of 0 or more Unicode characters
Strictly UNICODE. Default: UTF-8

No separate character type


A character is represented as a string with a length of 1

Wrapped in "double quotes" Backslash escapement

String
string
"

Any UNICODE character except " or \ or control character


\ " \ / b f n r t u

"

quotation mark reverse solidus solidus backspace formfeed newline carriage return horizontal tab 4 hexadecimal digits

Numbers
Integer Real Scientific No octal or hex No NaN or Infinity
Use null instead

Number

number
0 .

digit

digit 1 - 9 digit

e E +

digit
-

Booleans and Null


true false

Object
Objects are unordered containers of key/value pairs Objects are wrapped in { } , separates key/value pairs : separates keys and values Keys are strings Values are JSON values

Object

object
{

string

: ,

value

Object
{
"name": "Jack B. Nimble", "at large": true, "grade": "A", "format": { "type": "rect", "width": 1920, "height": 1080, "interlace": false, "framerate": 24 }

Array
Arrays are ordered sequences of values Arrays are wrapped in [] , separates values JSON does not talk about indexing.
An implementation can start array indexing at 0 or 1.

Array

array
[

value
,

Array
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

[
[0, -1, 0], [1, 0, 0], [0, 0, 1]

Arrays vs Objects
Use objects when the key names are arbitrary strings. Use arrays when the key names are sequential integers.

Example
{"section": "title": "Book-Signing Event", "signing": [ { "author": { "title": "Mr", "name": "Vikram Seth" }, "book": { "title": "A Suitable Boy", "price": "$22.95" } }, { "author": { "title": "Dr", "name": "Oliver Sacks" }, "book": { "title": "The Island of the Color-Blind", "price": "$12.95" } } ] }} section.title section.signing[0].author.title section.signing[1].book.title

JSON in JavaScript
JSON is a subset of the object literal notation of JavaScript.

Members can be retrieved using dot or subscript operators.


myJSONObject.bindings[0].method // "newURI"
42

Why is JSON better suited for AJAX?

JSON VS XML

43

Readability
JSON object: { "fullname": "Swati Kumar", "org": "Columbia", } XML file: <?xml version='1.0 encoding='UTF-8'?> <person> <fullname>Swati Kumar</fullname> <org>Columbia</org> </person>
44

Parsing
JSON object: var responseData = eval('(' + req.responseText + ')');
To access a composite element

eval('(' + req.responseText + ')').xyz.abc.value; XML


var root = req.responseXML; var name = root.getElementsByTagName(fullname); To access a composite element root.getElementsByTagName(xyz)*0].firstChild
45

Security Concerns
Instead eval() use JSON parser Link you HTML document to: http://www.json.org/json2.js, to be able to use parse() function var response = xhr.responseText var MyData = JSON.parse(response);

46

Conclusion
Ajax is an enabler for RIA (Rich Internet Applications). Ajax depends on asynchronous communication. The heart of Ajax is the XMLHttpRequest object Ajax can deal with different document types e.g. JSON and Plain text. Ajax is well established in most JavaScript libraries.
47

References
Look at the w3c Ajax tutorial examples:
http://www.w3schools.com/Ajax/ajax_examples.as p

JSON
http://www.json.org/

48

Vous aimerez peut-être aussi