javascript & ajax

39
1 JavaScript & AJAX CS 236607, Winter 2007/8

Upload: maxine

Post on 09-Jan-2016

70 views

Category:

Documents


2 download

DESCRIPTION

JavaScript & AJAX. CS 236607, Winter 2007/8. JavaScript. Overview. JavaScript is a scripting language most often used for client-side web development, and best known for this use in websites (as client-side JavaScript). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: JavaScript & AJAX

1

JavaScript & AJAX

CS 236607, Winter 2007/8

Page 2: JavaScript & AJAX

2

JavaScript

Page 3: JavaScript & AJAX

3

Overview JavaScript is a scripting language most often

used for client-side web development, and best known for this use in websites (as client-side JavaScript).

JavaScript is essentially unrelated to the Java programming language, though it copies many Java names and naming conventions.

JavaScript is used in many Web pages to add functionality, validate forms, detect browsers, and much more.

Page 4: JavaScript & AJAX

4

JavaScript by Examples

We will look at some JavaScript examples…

Page 5: JavaScript & AJAX

5

Hello World<html><body>

<script type="text/javascript">document.write(“<h1>Hello World!</h1>");

</script>

</body></html>

DOM treatment of the page

Page 6: JavaScript & AJAX

6

Document URL<html><body>The URL of this document is:

<script type="text/javascript">document.write(document.URL);

</script>

</body>

</html>

Page 7: JavaScript & AJAX

7

More Examples

Count the number of images in a document What are the coordinates of the cursor?

Notice events are thrown (events-driven)

Page 8: JavaScript & AJAX

Form Validation<html><head><script type="text/javascript">function validate() …(next slide)</script></head>

<body><form action="tryjs_submitpage.htm" onsubmit="return validate()">Name (max 10 chararcters): <input type="text" id="fname"

size="20"><br />Age (from 1 to 100): <input type="text" id="age" size="20"><br />E-mail: <input type="text" id="email" size="20"><br /><br/><input type="submit" value="Submit"> </form></body></html>

Page 9: JavaScript & AJAX

Form Validation (Cont.)<script type="text/javascript">function validate(){ var at=document.getElementById("email").value.indexOf("@"); var age=document.getElementById("age").value; var fname=document.getElementById("fname").value; submitOK="true";

if (fname.length>10){alert("The name must be less than 10 characters");submitOK="false"; }

if (isNaN(age)||age<1||age>100) {alert("The age must be a number between 1 and 100");submitOK="false"; }

if (at==-1) {alert("Not a valid e-mail!");submitOK="false"; }

if (submitOK=="false") {return false; }

}</script>

DOM Objects

JavaScript Function

Object Property

Page 10: JavaScript & AJAX

10

AJAX

Page 11: JavaScript & AJAX

11

Where Were We Before AJAX?

Static pages give the illusion of interactivity through standard form submissions.

Form submissions result in full page loads.

Page 12: JavaScript & AJAX

12

So, What’s The Problem? Many actions only manipulate small portions of the

page but the entire page must be reloaded. Server responses contain the entire page content

rather than just the portion being updated. Loading entire pages typically results in several

additional HTTP requests for images, style sheets, scripts, and any other content that may be on the page.

Page 13: JavaScript & AJAX

13

AJAX - Asynchronous JavaScript and XML An interface that allows for the HTTP

communication without page refreshment. Web pages are loaded into an object within the

script (e.g., JavaScript) execution and integrated with the page content.

Thus, the Web page can communicate with the server without refreshing the whole page.

Page 14: JavaScript & AJAX

14

Real-Life Examples of AJAX Apps Google maps

http://maps.google.com/ Goolgle Suggest

http://www.google.com/webhp?complete=1&hl=en Gmail

http://gmail.com/ Yahoo Maps (new)

http://maps.yahoo.com/ Many more…

Page 15: JavaScript & AJAX

15

AJAX Components JavaScript

DOM XMLHttpRequest object (XHR) XML

Page 16: JavaScript & AJAX

16

Ajax Fundamentals

Ajax uses a three-step process:1. Request a URL from JavaScript code on the client.

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

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

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

Page 17: JavaScript & AJAX

17

The Server sideDid we reduce the load on the server? Ajax newcomers sometimes mistakenly believe

that Ajax, because it provides a more responsive user interface, reduces server-side traffic.

In fact, Ajax applications typically have more server-side traffic because each Ajax request involves a trip to the server. Because those requests are asynchronous, however,

Ajax creates the perception of a more responsive UI, though it typically does not reduce the load on the server.

Page 18: JavaScript & AJAX

18

So, How Does It Work? JavaScript is used to:

Create and control instances of the XMLHttpRequest (XHR) object.

Provide handlers for responses. Manipulate the DOM.

The XMLHttpRequest object: Allows scripts to perform HTTP client functionality. Supports GET and POST operations.

Page 19: JavaScript & AJAX

19

Launching HTTP Requests

Typically, 3 steps are required:

1.1. Construct and configure an XMLHttpRequest object

2.2. Launch the request

3.3. Process the response

Page 20: JavaScript & AJAX

20

Constructing an XMLHttpRequest

For Mozilla:

For Microsoft Explorer:

var request = new XMLHttpRequest();

var request = new ActiveXObject("Microsoft.XMLHTTP");

Page 21: JavaScript & AJAX

21

Configuring an XMLHttpRequest

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

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 false will be discussed later

Page 22: JavaScript & AJAX

22

Launching the Request

request.send(content )

• content is the posted in a POST request

• content can be "null" or empty

Page 23: JavaScript & AJAX

Reading the Response

request.responseText

• The response as flat text

request.responseXML

• The response as a (DOM) Document object

• Available if response Content-Type is text/XML

request.status request.statusText

request.getAllResponseHeaders()

request.getResponseHeader("header")

Page 24: JavaScript & AJAX

24

<html>

< head>

< title<Jokes>/title>

< script type="text/javascript">

...2 slides ahead...

/< script>

/< head >

An Example

Page 25: JavaScript & AJAX

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

>h1<Select a Joke:>/h1<

>p<>select onchange="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<

An Example (Cont.)

Page 26: JavaScript & AJAX

>script type="text/javascript"<

var jDiv;

function init() { jDiv = document.getElementById("jokediv");}

function setJoke(value) {

request = new XMLHttpRequest();

request.open("GET","joke"+value+".txt",false);

request.send(null);

if(request.status==200){jDiv.innerHTML=request.responseText;}

else {jDiv.innerHTML = ">i<Cannot load joke...>/i<";}

}

>/script<

What if we didn’t get yet the response in this stage?

Page 27: JavaScript & AJAX

27

Example (Cont.)

Our examples use “false" in the third parameter of open(). This parameter specifies whether the request should be

handled asynchronously. True means that the script continues to run after

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

Let’s see how it works, and how it is saved on the Tomcat server.

Page 28: JavaScript & AJAX

28

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 29: JavaScript & AJAX

29

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 30: JavaScript & AJAX

30

XMLHttpRequest States (Cont.)

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

Use request.abort() to stop the request

Page 31: JavaScript & AJAX

31

var request;

function setJoke(value) {

request = new XMLHttpRequest();

request.open("GET","joke"+value+".txt",true);

request.onreadystatechange = updateJokeDiv;

request.send(null);

}

Asynchronous Example

Page 32: JavaScript & AJAX

function updateJokeDiv() {

if(request.readyState>4) {

jokeDiv.innerHTML = ">i<Loading...>/i<";

return; }

if(request.status==200) {

jokeDiv.innerHTML = request.responseText; }

else {

jokeDiv.innerHTML = ">i<Cannot load joke!>/i<"; }

}

An Example (Cont.)

Page 33: JavaScript & AJAX

33

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 34: JavaScript & AJAX

34

>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 35: JavaScript & AJAX

>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 36: JavaScript & AJAX

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 37: JavaScript & AJAX

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 38: JavaScript & AJAX

38

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.

The Prototype Library is one option.

Page 39: JavaScript & AJAX

39

Resources

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

Geary, Cay S. Horstmann