• Nie Znaleziono Wyników

AJAX, JSON, Deferred objects

N/A
N/A
Protected

Academic year: 2021

Share "AJAX, JSON, Deferred objects"

Copied!
19
0
0

Pełen tekst

(1)

AJAX, JSON, Deferred objects

Maciej Grzenda, Michał Okulewicz Warsaw University of Technology

Faculty of Mathematics and Information Science

M.Grzenda@mini.pw.edu.pl, M.Okulewicz@mini.pw.edu.pl

http://www.mini.pw.edu.pl/~okulewiczm

(2)

http://www.mini.pw.edu.pl/~okulewiczm

p. 2

Maciej Grzenda & Michał Okulewicz

AJAX?

• AJAX = Asynchronous JavaScript+XML

• General idea:

– Use JavaScript and XML-based messages to communicate from within a web page with the server without refreshing the HTML page at the same time

– „With AJAX, we are taking a bunch of dusty old technologies and stretching them well beyond their original scope", AJAX in Action, Manning, 2006

http://maps.google.com is an example of an AJAX-

based application

(3)

p. 3

Web browser

AJAX – browser-server interaction

The JS function calling the server

The JS function handling the answer

Web server

1 2

3a 3b 3c

Steps:

1. The JS function requests a document from the server

2. The server answers the HTTP request in a standard manner 3a, 3b, 3c The handling function

is informed that the data starts to arrive, has arrived and is complete, respectively

(subject to browser version)

(4)

http://www.mini.pw.edu.pl/~okulewiczm

p. 4

Maciej Grzenda & Michał Okulewicz

Sample AJAX code – part I

<!DOCTYPE html>

<html>

<head>

<title>Ajax example</title>

<script type="text/javascript">

var req=null;

var console=null;

var READY_STATE_UNINITIALIZED=0;

var READY_STATE_LOADING=1;

var READY_STATE_LOADED=2;

var READY_STATE_INTERACTIVE=3;

var READY_STATE_COMPLETE=4;

function loadXMLDoc(url) {

if (window.XMLHttpRequest) { req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");

}

if (req) {

req.onreadystatechange = processReqChange;

req.open("GET", url, true);

req.send(null);

}

}

The loadXMLDoc function takes into

account both Mozilla and IE browsers

(5)

p. 5

AJAX code – part II

function processReqChange(){

var ready=req.readyState;

var data=null;

if (ready==READY_STATE_COMPLETE){

data=req.responseText;

alert("Received data. This data will be inserted as a part of HTML code. The data is: "+data);

console.innerHTML=data;

}else{

data="loading...["+ready+"]";

var newline=document.createElement("div");

messages.appendChild(newline);

var txt=document.createTextNode(data);

newline.appendChild(txt);

} }

window.onload=function(){

console=document.getElementById('console');

loadXMLDoc("http://www.w3.org/TR/CSS21/");

}

</script>

</head>

<body>

<div id="messages"></div>

<div id="console"></div>

</body>

</html>

The example is adapted from the code in "AJAX in Action", Manning, 2006 1. JavaScript event handler for

onLoad event is programmatically defined

2. The code may not work due to single origin restrictions in some browsers. If so, document name should be changed to local file.

ajax_sample_1.html

(6)

http://www.mini.pw.edu.pl/~okulewiczm

p. 6

Maciej Grzenda & Michał Okulewicz

Example 1 - discussion

Asynchronous connection is established in the following way:

• first JS function to be used once the data becomes available is declared:

req.onreadystatechange = processReqChange;

• the HTTP connection in the background to the url is initiated, in the example it is based on HTTP GET method:

req.open("GET", url, true);

• finally, the empty query string for the request is declared:

req.send(null);

Notice that the asynchronous connection and data transmission does not affect the web site displayed in the browser. On the contrary all the processing happens in the background. All the actions are performed in the asynchronous manner i.e. the

browser is not suspended until the data produced by the URL arrives.

(7)

p. 7

Example 1 - discussion

function processReqChange(){

var ready=req.readyState;

var data=null;

if (ready==4){

data=req.responseText;

alert("Received data: "+data);

}else{

data="loading...["+ready+"]";

}

The handler function is activated a number of times for the same request. In

particular, it might be activated when the content from the url starts to arrive and

when it is completely received. Therefore, the handling function should check

readyState property not to start the processing of requested URL too early.

(8)

http://www.mini.pw.edu.pl/~okulewiczm

p. 8

Maciej Grzenda & Michał Okulewicz

Real-life request

Asynchronous connection is established in the following way:

• first JS function to be used once the data becomes available is declared:

req.onreadystatechange = processReqChange;

• the HTTP connection to the url is initiated, it is based on a requested method (GET or POST) in asynchronous (async=true) or not

(async=false) mode:

req.open(method, url, async);

• Content-type is declared so as to transmit request parameters appropriately:

req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

• finally, the query string for the request can be declared:

req.send(params);

The params variable for POST requests should contain a query string i.e.

parameter values e.g. params="name=aaa&surname=bbb"

(9)

p. 9

Query string

• In GET method:

– Arguments are sent with the address – Example:

req.open("GET","script?name=John&surname=Major",true);

req.send();

• In POST method:

– Arguments sent with send () method; content type is specified, too – Example:

req.open("POST","script",true);

req.setRequestHeader("Content-type","application/x-www- form-urlencoded");

req.send("name=John&surname=Major");

(10)

http://www.mini.pw.edu.pl/~okulewiczm

p. 10

Maciej Grzenda & Michał Okulewicz

AJAX in jQuery

• jQuery (and other JS libraries e.g. Prototype) give an easier access to AJAX methods

• A general $.ajax() method

– $.ajax(url,{

type: request_HTTP_method,

contentType: request_MIME_type, data: query_data,

success: success_handler(data), failure: failure_handler(data), ...

})

• Additional shorthand methods

– $.post/get(url,query_data,success_handler(data),data_type)

– $(selector).load(url,query_data,success_handler(data))

(11)

p. 11

AJAX: HTML and JSON

• XML is not the most convenient of the formats to be processed in JavaScript

• It is better to generate parts of the web pages already in XML

• It is even better to prepare a web accessible general

purpose API generating JSON responses

(12)

http://www.mini.pw.edu.pl/~okulewiczm

p. 12

Maciej Grzenda & Michał Okulewicz

JSON: JavaScript Object Notation

• JSON is a subset of the object literal notation of JavaScript

• JSON can be used to easily convert text strings into JavaScript objects and vice versa

• In fact, JSON is based on two structures:

– A collection of name and value pairs, which can be transformed into an object,

– A list of values (possibly objects), which can be transformed into an array or a list

• Thus, the text sent from the server-side script can be easily transformed into JavaScript object and used in the web

interface layer

• JSON standard is widely supported in many programming languages incl. Java, C, C++, C#, PHP. As a consequence it can be easily used for structured data exchange.

www.json.org can be consulted for any JSON details going beyond the scope

of this lecture. http://www.json.org/js.html is devoted to JSON in JavaScript.

(13)

p. 13

JSON example I – part I

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSON test</title>

<script language="JavaScript" src="json2.js" >

</script>

<script language="JavaScript">

var myJSONTestObject = {"productList": [

{"book_id": "121", "title": "Java in 24 hours",

"year_of_publication": "2002"},

{"book_id": "187", "title": "UNIX Administration",

"year_of_publication": "1997"},

{"book_id": "203", "title": "Oracle DBA Handbook",

"year_of_publication": "1999"}

]

}; json2.org comes from www.json.org and provides JSON object declaration.

The JSON object is used to perform necessary conversions.

myJSONTestObject is a JS object initialised using JSON notation.

(14)

http://www.mini.pw.edu.pl/~okulewiczm

p. 14

Maciej Grzenda & Michał Okulewicz

JSON Example I – part II

alert("The first item in an array:

"+myJSONTestObject.productList[0].title+" published in

"+myJSONTestObject.productList[0].year_of_publication);

var myJSONText = JSON.stringify(myJSONTestObject);

alert("Complete JSON representation of an object: "+myJSONText);

The JavaScript object is converted to its JSON text representation.

(15)

p. 15

JSON Example I – part III

alert("Complete JSON representation of an object describing the first book

"+JSON.stringify(myJSONTestObject.productList[0]));

}

</script>

</head>

<body onLoad="uploadBooks()">

….

</body>

</html>

The attributes of any JS object can be easily converted into its JSON text

representation. The text can be submitted to the server-side script to restore the

(16)

http://www.mini.pw.edu.pl/~okulewiczm

p. 16

Maciej Grzenda & Michał Okulewicz

JSON – reverse operation

var myObject = eval('(' + myJSONText + ')');

alert("The title of the first book is:

"+myObject.productList[0].title);

The JSON string contained in myJSONText variable is used to create the JavaScript object basing on its JSON text representation. The JSON text representation can be easily created by the server-side script and sent back to the browser in order to obtain a complex JavaScript object basing on it.

However, this may cause significant security problems. The eval() function may potentially

call any code and inject risky code into the web site. Still JSON gives you a chance to obtain

JavaScript objects without parsing the text received from the server at all.

(17)

p. 17

JSON – syntax rules

• An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

– Example:

{"book_id": "121", "title": "Java in 24 hours",

"year_of_publication": "2002"}

• An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

– Example:

[

{"book_id": "121", "title": "Java in 24 hours",

"year_of_publication": "2002"}, …

{"book_id": "203", "title": "Oracle DBA Handbook",

"year_of_publication": "1999"}

]

• A value can be a string in double quotes, or a number, or true or false or null, or an

object or an array. These structures can be nested.

(18)

http://www.mini.pw.edu.pl/~okulewiczm

p. 18

Maciej Grzenda & Michał Okulewicz

Deferred objects

• In order to provide a proper dependence and workflow of

asynchronous AJAX calls one should rely on deffered objects mechanism exposed (at least in jQuery) by AJAX calls

var a = $.Deferred();

var b = $.Deferred();

$.when(a,b).then(function(dataa,datab) { console.info(dataa+datab);

});

$(document).ready( function () { a.resolve(1);

b.resolve(2);

});

(19)

p. 19

AJAX call as deferred

var a = $.ajax(url1);

var b = $.ajax(url2);

$.when(a,b) .then(

function(dataa,datab) {

console.info(dataa+datab);

},

function () {

console.info('Query failed');

});

Cytaty

Powiązane dokumenty

Each subsequent absence should be made up for in the form of an oral answer during the office hours within two weeks of the absence or the cause of the absence - otherwise the

Space, Voice, and Body: Company on the Screen ...65 BETWEEN THE

Its aim is to make accessible scholar- ship that addresses important issues in modern and contem- porary English-language literature, and also scholarship that deals with

Besides these the proof uses Borel–Carath´ eodory theorem and Hadamard’s three circles theorem (the application of these last two theorems is similar to that explained in [4], pp..

The IBAN account numbers in Poland consist of the country prefix (PL) and then 26 digits, where the first two are the control sum digits (12 in the above example), next 4

• Create a GeoConverter.aspx WebForm for converting the geographical coordinates between the decimal and degrees minutes seconds format. • The user enters and submits the

• The content type &#34;multipart/form-data&#34; should be used for submitting forms that contain files, non- ASCII data, and binary data.. • The content

– Do not display the form if the cookie with login is present – Add a link and a WebForm to delete the cookie. – A link displays the login from