Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010."— Presentation transcript:

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

2 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 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 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 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 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 7 XMLHttpRequest States The XMLHttpRequest goes through several states: In the request configuration, you can define a function to call upon state change: 0 0 not initialized 1 1 loading 2 2 loaded 3 3 interactive 4 4 complete request.onreadystatechange = functionName

8 8 XMLHttpRequest States (Cont.) Use request.readyState to get the current state of the request Use request.abort() to stop the request

9 9 Jokes... 2 slides ahead... Asynchronous Example

10 Current date on server: ? Select a Joke: Joke 1 Joke 2 Joke 3 Asynchronous Example (Cont.)

11 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 = " Cannot load joke... ";} } Asynchronous Example (Cont.) Just like the previous tutorial example

12 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 = " Can not tell server time!"; } Asynchronous Example (Cont.)

13 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 14 Country List … Select a Continent: XML+AJAX Example

15 Asia Africa Europe XML+AJAX Example (Cont.)

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

17 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 18 Advanced Topics

19 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

20 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 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 The Prototype Library jQuery, dojo, GWT are more advanced options jQuerydojoGWT ZK also offers JSP integration ZK JavaScript Frameworks Comparison (Wikipedia) JavaScript Frameworks Comparison

22 Debug A good tool (highly recommended) for debug is Firebug on Firefox. Firebug There are other tools – almost every browser has a built in JavaScript debug capability (at some level). 22

23 23 Resources DaveFancher.com Coreservlets.com Hebrew University Course javapassion.com W3 Schools Wikipedia Core JavaServer Faces(2nd Edition) / David Geary, Cay S. Horstmann


Download ppt "1 AJAX – Asynchronous JavaScript and XML – Part II CS 236369, Spring 2010."

Similar presentations


Ads by Google