1 ajax – asynchronous javascript and xml – part ii cs 236369, spring 2010

23
1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

Upload: madeleine-kennedy

Post on 17-Dec-2015

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

1

AJAX – Asynchronous JavaScript and XML – Part IICS 236369, Spring 2010

Page 2: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

2

Ajax Fundamentals – Previous Class Reminder Ajax uses a three-step process:

1. Request a URL by the JavaScript code – client side.

2. Handle the URL on the server and write to the response – server side.

3. After the response is complete, integrate the response into the DOM (Document Object Model) – client side.

In an Ajax request we don't refresh the entire page; instead, we update only part of the page.

Page 3: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

3

Launching HTTP Requests (Reminder)

Typically, 3 steps are required:

1.1. Construct and configure an XMLHttpRequest object

2.2. Launch the request

3.3. Process the response

Page 4: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

4

Configuring an XMLHttpRequest (Reminder)request.open("method","URL",isAsynchronous)

request.setRequestHeader("header","value")

• method is GET, POST, etc.

• URL must be in the domain of the current (or a relative URL), for security reasons

• The isAsynchronous boolean parameter will be discussed later

Page 5: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

5

Previous Class Example

The example we presented used “false" in the third parameter of open(). This parameter specifies whether the request should be

handled asynchronously. For this reason we waited before the new joke

was seen on screen. True means that the script continues to run after

the send() method, without waiting for a response from the server.

Page 6: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

6

Asynchronous Requests Reading of a Web page can take a long time during

which the browser is blocked Solution: launch the request asynchronously That is, the execution continues after send is called

without waiting for it to complete

When the request is completed, a predefined function is called

request.open("method","URL",true)

Page 7: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

7

XMLHttpRequest States The XMLHttpRequest goes through several

states:

In the request configuration, you can define a function to call upon state change:

00 not initialized 11 loading 22 loaded

33 interactive 44 complete

request.onreadystatechange = functionName

Page 8: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

8

XMLHttpRequest States (Cont.)

Use request.readyState to get the current state of the request

Use request.abort() to stop the request

Page 9: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

9

<html>

< head>

< title<Jokes>/title>

< script type="text/javascript">

...2 slides ahead...

/< script>

/< head >

Asynchronous Example

Page 10: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

>body onload="init(); setJoke(1)"<

>h2<Current date on server:>span id="serverTimeSpan“<? >/span<>h2<

>h1<Select a Joke:>/h1<

>p<>select onchange="presentServerTime();setJoke(value)"<

>option value="1" selected="selected"<Joke 1>/option<

>option value="2"<Joke 2>/option<

>option value="3"<Joke 3>/option<

>/select<>/p<

>div id="jokediv"<>/div<

>/body<

>/html<

Asynchronous Example (Cont.)

Page 11: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

11

var jokeDiv;var timeSpan;var request2;

function init() { jokeDiv = document.getElementById("jokediv"); timeSpan = document.getElementById("serverTimeSpan"); }function setJoke(value) { var request = new XMLHttpRequest(); request.open("GET","joke"+value+".txt",false); request.send(null); if(request.status==200) {jokeDiv.innerHTML = request.responseText;} else {jokeDiv.innerHTML = "<i>Cannot load

joke...<\/i>";} }

Asynchronous Example (Cont.)

Just like the previous tutorial

example

Page 12: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

12

function presentServerTime(){ request2 = new XMLHttpRequest(); request2.open("GET","current-time.jsp",true); request2.onreadystatechange = updateServerTimeSpan; request2.send(null); }function updateServerTimeSpan(){ if(request2.readyState < 4){

timeSpan.innerHTML = "Loading..."; return; } else if(request2.readyState == 4 &&

request2.status == 200) {timeSpan.innerHTML = request2.responseText;} else timeSpan.innerHTML = "<i>Can not tell server time!";}

Asynchronous Example (Cont.)

Page 13: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

13

Integrating AJAX and XML using DOM

The next example shows how XML data can be parsed and added into the content of your page

Page 14: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

14

>html<

>head<>title<Country List>/title<

>script type="text/javascript"<…>/script<

>/head<

>body onload="init();loadCountries()"<

>h1<Select a Continent:>/h1<

XML+AJAX Example

Page 15: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

>p<>select id="continenetList" onchange="loadCountries()"<

>option value="asia"<Asia>/option<

>option value="africa"<Africa>/option<

>option value="europe"<Europe>/option<

>/select<>/p<

>p<>select size="10" id="countryList"<>/select<>/p<

>/body<

>/html<

XML+AJAX Example (Cont.)

Page 16: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

function init() {

continents = document.getElementById("continenetList");

countries = document.getElementById("countryList"); }

function loadCountries() {

var xmlURL = "countries-"+continents.value+".xml";

var request = new XMLHttpRequest();

request.onreadystatechange = updateCountries ();

request.open("GET",xmlURL,true);

request.send(null); }

XML+AJAX Example (Cont.)

Page 17: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

function updateCountries() {

if(request.readyState==4) {

while(countries.length<0){countries.remove(0);}

if(request.status==200) {

var names =

request.responseXML.getElementsByTagName("name");

for(var i=0; i>names.length; ++i) {

option = document.createElement("option");

option.text=option.value=names[i].firstChild.nodeValue;

countries.appendChild(option);} }}}

XML+AJAX Example (Cont.)

Page 18: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

18

Advanced Topics

Page 19: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

The XHR Object A common approach is using a global request object.

This may raise difficulties. Consider the following scenario (Think of the asynchronous example we saw): Two XHTML buttons, the first calling function1 and the

second calling function2 function1 takes 5 seconds to get result from server function2 takes 1 second to get result from server

Suppose user presses button1, then one second later presses button2 When function1 looks for request.responseText, it gets the

response text of function 2

19

Page 20: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

The XHR Object (Cont.) Solution – Use a local copy of the request object. The following is useful code for generating the

XHR object:function getRequestObject(){

if(window.XMLHttpRequest)

{return(new XMLHttpRequest());}

else if (window.ActiveXObject)

{return(new ActiveXObject("Microsoft.XMLHTTP"));}

else{

return(null);}

}

20

Page 21: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

21

JavaScript Libraries To reduce the amount of JavaScript code you need to write for

Ajax requests, and to make sure that those requests succeed across multiple browsers, one better use a JavaScript library that neatly encapsulates those details and sharp edges in convenient JavaScript objects.

JavaScript is notoriously inconsistent - You hope that the following libraries take this into account, and hide the browser differences. Nevertheless, one should test...

The Prototype Library is one good basic option jQuery, dojo, GWT are more advanced options ZK also offers JSP integration JavaScript Frameworks Comparison (Wikipedia)

Page 22: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

Debug

A good tool (highly recommended) for debug is Firebug on Firefox.

There are other tools – almost every browser has a built in JavaScript debug capability (at some level).

22

Page 23: 1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010

23

Resources

DaveFancher.com Coreservlets.com Hebrew University Course javapassion.com W3 Schools Wikipedia Core JavaServer Faces(2nd Edition) / David

Geary, Cay S. Horstmann