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

Preview:

Citation preview

1

AJAX – Asynchronous JavaScript and XML – Part IICS 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.

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

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

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.

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)

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

8

XMLHttpRequest States (Cont.)

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

Use request.abort() to stop the request

9

<html>

< head>

< title<Jokes>/title>

< script type="text/javascript">

...2 slides ahead...

/< script>

/< head >

Asynchronous Example

>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.)

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

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.)

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

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

>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.)

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.)

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.)

18

Advanced Topics

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

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

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)

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

23

Resources

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

Geary, Cay S. Horstmann

Recommended