51

AJAX Transport Layer

Embed Size (px)

DESCRIPTION

Day 1 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It covers XMLHttpRequest, iframe, img cookie transport, script transport, JSONP, comet.

Citation preview

Page 1: AJAX Transport Layer
Page 3: AJAX Transport Layer

Our roadmap

Page 4: AJAX Transport Layer

AJAX... not just for toilet cleaning anymore

• AJAX = Asynchronous JavaScript and XML

• Ajax is set of technologies that allow web applications to provide rich interaction without whole page refreshing.

Page 5: AJAX Transport Layer

Ajax: Classic Web Application

1) Browser makes request to server2) Server sends HTML/CSS response

Page 6: AJAX Transport Layer

Ajax: Ajax Web Application

1) Browser makes request to server asynchronously2) Server sends XML/JSON response3) AJAX Engine processes response

Page 7: AJAX Transport Layer

XMLHttpRequest

Page 8: AJAX Transport Layer

5) The XMLHttpRequest object receives the XML data and calls a callback to process it.

1) User generates an event (e.g. button click)

2) System creates an XMLHttpRequest and configures with request parameters.

3) The XMLHttpRequest object makes an asynchronous request to the web server.4) Web server returns XML(other) object with data.

XMLHttpRequest: Fetching data flow

Page 9: AJAX Transport Layer

// event handler attribute EventListener onreadystatechange;

// state const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; const unsigned short LOADING = 3; const unsigned short DONE = 4; readonly attribute unsigned short readyState;

// request void open(in DOMString method, in DOMString url); void open(in DOMString method, in DOMString url, in boolean async); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password); void setRequestHeader(in DOMString header, in DOMString value); void send(); void send(in DOMString data); void send(in Document data); void abort();

// response DOMString getAllResponseHeaders(); DOMString getResponseHeader(in DOMString header); readonly attribute DOMString responseText; readonly attribute Document responseXML; readonly attribute unsigned short status; readonly attribute DOMString statusText;

XMLHttpRequest: XHR InterfaceXHR State

opensendabort

Response (Text/XML)

event listener

Page 10: AJAX Transport Layer

XMLHttpRequest: How to get XHRfunction getXHR() { var request = null; if (typeof XMLHttpRequest != 'undefined') { request = new XMLHttpRequest(); } else { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } return request; }

Page 11: AJAX Transport Layer

XMLHttpRequest: Using XHR

var READY_STATE_COMPLETE=4;

var request = getXHR();request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { //process data } //Some error else { //process error } }};request.open(method,url,true);request.send(null);

1

2

34

5.2

5.1

Page 12: AJAX Transport Layer

XMLHttpRequest: An exampleA classic example is linked drop-downs.

Regions Cities

Page 13: AJAX Transport Layer

XMLHttpRequest: Supported methods• GETRequests a representation of the specified resource. By far the most common method used on the Web today.

• POSTSubmits data to be processed (e.g. from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

• HEADAsks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.

• PUTUploads a representation of the specified resource.

• DELETEDeletes the specified resource.

• OPTIONSThis method allows the client to determine the options and/or requirements associated with a resource.

Page 14: AJAX Transport Layer

XMLHttpRequest: GET method

var READY_STATE_COMPLETE=4;var request = getXHR();request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { //process data } //Some error else { //process error } }};request.open("GET", "/path?param1=value1&param2=value2",true);

request.send(null);

1

2

3

4

5.2

5.1

is asynchronous?

Page 15: AJAX Transport Layer

XMLHttpRequest: POST method

var READY_STATE_COMPLETE=4;var request = getXHR();request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { //process data } //Some error else { //process error } }};request.open("POST", "/path",true);

request.send("param1=value1&param2=value2");

1

2

3

4

5.2

5.1

is asynchronous?

Page 16: AJAX Transport Layer

XMLHttpRequest: Features

• object available in IE/Mozilla/Opera/Safari• synchronous and asynchronous requests• POST and GET support

Page 17: AJAX Transport Layer

XMLHttpRequest: Pros and Cons

+ not limited to XML+ asynchronous calls+ can receive HTTP status codes/headers+ supported GET and POST

- back button problems- same-origin policy

Page 18: AJAX Transport Layer

XMLHttpRequest: Same-origin policyThe philosophy of the same origin policy is simple: the browser should not trust content loaded from arbitrary websites.

The term "origin" is defined using the domain name, protocol and port.

URL Outcome Reason

http://www.example.com/dir2/other.html Success Same protocol and host

http://www.example.com/dir/inner/other.html Success Same protocol and host

http://www.example.com:81/dir2/other.html Failure Same protocol and host but different port

https://www.example.com/dir2/other.html Failure Different protocol

http://en.example.com/dir2/other.html Failure Different host

http://example.com/dir2/other.html Failure Different host

Page 19: AJAX Transport Layer

Questions?

Page 20: AJAX Transport Layer

iframe transport

Page 21: AJAX Transport Layer

iframe transport: Fetching data flow

5) The IFrame object receives the XML data and fires a load event.

1) User generates an event (e.g. button click)

2) System creates a hidden IFrame and configures with request parameters.

3) The IFrame element makes an request to the web server.4) Web server returns XML(other) object with data.

Page 22: AJAX Transport Layer

iframe transport: How to use

var iframe = document.createElement("iframe");iframe.width="0";iframe.height="0";...iframe.onload = bind(this.callback, this);...iframe.src = this.url + "?" + this.getRequestString();...document.body.appendChild(this.iframe);

1

2

4

3GET

{ }In order to use POST you need to create <form> and fill it dynamically.

Page 23: AJAX Transport Layer

iframe transport: How to use

var iframe = document.createElement("iframe");iframe.width="0";iframe.height="0";...iframe.onload = bind(this.callback, this);...iframe.src = this.url + "?" + this.getRequestString();...document.body.appendChild(this.iframe);

1

2

3

4

GET

<iframe> <!-- ... --> <script type="text/javascript"> window.parent.someFunction(/*data here*/); </script> <!-- ... --></iframe>

Page 24: AJAX Transport Layer

iframe transport: An exampleLinked drop-downs example.

Regions Cities

Page 25: AJAX Transport Layer

iframe transport: Pros and Cons

+ wide browser compatibility

- browser history- iframe not supported by XHTML strict- cross-domain policy

Page 26: AJAX Transport Layer

iframe transport: Cross-domain policy

...iframe.src = this.url + "?" + this.getRequestString();...<iframe> <!-- ... --> <script type="text/javascript"> window.parent.handleIframeResponse(/*data here*/); </script> <!-- ... --></iframe>

different than currenthttp://host:port/path

Page 27: AJAX Transport Layer

Questions?

Page 28: AJAX Transport Layer

img cookie transport

Page 29: AJAX Transport Layer

img cookie transport: What is cookie?Technically, cookies are arbitrary pieces of data chosen by the Web server and sent to the browser.

Page 30: AJAX Transport Layer

Relevant count of maximum stored cookies per domain for the major browsers are:

img cookie transport: Cookies limitations

Firefox 2

Firefox 3

Opera 9.30

IE 6

IE 7

Safari

0 12.5 25.0 37.5 50.0

Safari has no limit.

Cookies must be smaller than 4 kilobytes. Internet Explorer imposes a 4KB total for all cookies stored in a given domain.

Page 31: AJAX Transport Layer

img cookie transport: Fetching data flow

1) Create <img> with request URL and append it to body. Browser makes a request to the server.

2) Server sets cookies and sends response to the client.

3) Client checks cookies after some time interval.

Page 32: AJAX Transport Layer

img cookie transport: An example

...

var img = document.createElement("img");img.width = "0";img.heigth = "0";img.src = this.url + "?" + this.getRequestString(this.data);

...document.body.appendChild(this.img);...

setTimeout(bind(this.callback,this),this.interval);

1

2

4

3

Page 33: AJAX Transport Layer

img cookie transport: Pros and Cons

+ lightweight+ really really extra wide compatibility

- limited data due to GET and cookie limits

Page 34: AJAX Transport Layer

Questions?

Page 35: AJAX Transport Layer

script transport

Page 36: AJAX Transport Layer

script transport: Fetching data flow

1) Create <script> element with given src attribute. Browser makes request to the server.

2) Server returns JSON data wrapped in function call.

3) Client runs function in own context.

Page 37: AJAX Transport Layer

script transport: JSON? What is it?

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

• It is easy for humans to read and write. • It is easy for machines to parse and generate. • It is based on a subset of the JavaScript Programming Language.• It is a text format that is completely language independent.

Page 38: AJAX Transport Layer

script transport: JSON? What is it?

{ {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } } }

Page 39: AJAX Transport Layer

script transport: An example

del.icio.us mashup

Page 40: AJAX Transport Layer

script transport: Pros and Cons

+ exempt from Same Origin restriction+ less overhead (headers, cookies)

- JSON only- GET method only

Page 41: AJAX Transport Layer

script transport: JSONP extension

Pass a name of callback function as jsonp parameter.

http://somehost:port/path?jsonp=funcName&param1=value1

jsonp + "(" + jsonResult + ");"

Page 42: AJAX Transport Layer

Questions?

Page 43: AJAX Transport Layer

comet

Page 44: AJAX Transport Layer

comet: Intro

Named after kitchen cleaning.

Page 45: AJAX Transport Layer

comet: What is it?

Fundamentally, [Comet applications] all use long-lived HTTP connections to reduce the latency with which messages are passed to the server.

In essence, they do not poll the server occasionally. Instead the server has an open line of communication with which it can push data to the client.

Page 46: AJAX Transport Layer

comet: Who’s using it?

Page 47: AJAX Transport Layer

comet: Classic Ajax Application

Page 48: AJAX Transport Layer

comet: Comet Application

Page 49: AJAX Transport Layer

comet: An example

Highly interactive applications like chats, real-time games, etc.

Page 50: AJAX Transport Layer

comet: Pros and Cons+ low latency+ event-based server push

- client 2 connection limit- pragmatically requires custom server component

CometdLightStreamer...

Page 51: AJAX Transport Layer

Questions?