asynchronous javasript and xml

53
Java III--Copyright © 2007 Tom Hunter

Upload: manglam-jaiswal

Post on 26-May-2015

102 views

Category:

Education


1 download

TRANSCRIPT

Page 1: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

Page 2: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAXAsynchronous JavaScript And

XML

Page 3: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:

Introduction

Page 4: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

• AJAXAJAX is a term coined by Mr. JesseJames Garrett of Adaptive Path to describe a type of web programming that transfers information to and from the server without doing a server post.

• This is not really new technologynot really new technology, rather it is a clever combination ofsomewhat new and mostly existing technologies, such as JavaScript—the language many web programmers love to hate–and a special object pioneered by [holding my nose] Microsoft with CSS thrown into the mix.

AJAX: Introduction*

Jesse James Garrett

Page 5: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

• AJAX is a large topic that could fill hundreds of slides.

• In this lecture, I intend only to present an introductionintroduction to AJAX.

• This lecture will not be comprehensive.

• This lecture will get you up and running with AJAX.

AJAX: Introduction*

Page 6: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:A Quick Overview of How it Works

Page 7: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

• First we will cover the round trip of how AJAX works and then we will circle around and show how each of the steps work in detail.

AJAX: A Quick Overview of How it Works

Page 8: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called. 3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

Page 9: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

There are inconsistencies in the way that different browsers implement this step. Therefore, we are forced to determine which browser the user is using before we decide which type of object to create.

Page 10: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

This can be called when the page first loads or at anytime after the page has been loaded. This can be triggered by some user-triggered event or by a status change.

Page 11: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

Here, we send the request to a URL—also sending along parameters if we wish—and then registering a callback handler that will wait for the response.

Page 12: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

Actually, the callback handler that we register will receive several responses during the processing of the request. However, only a particular one—with a special status of “4”—will contain the response information we sought.

Page 13: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.

AJAX: A Quick Overview of How it Works

Finally, we pull out the information from the request that we need and use that to modify the HTML of our page. There are several ways of doing that, which we shall see.

Page 14: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:A Special Request Object is Created

Page 15: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A Special Request Object Is Created

• When the page loadsloads, it executes the JavaScript function createRequestObject().

When this page is loaded for the first time, this line executes the named function. The function’s declaration is right above it. So, while we stare at the newly loaded page, this http object has already been created and it waits around for us to do something.

Page 16: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

• In the AJAX world, we have a problem. The primary object that AJAX relies on was implemented differently by different browsers such as MS IE, Mozilla Firefox, etc.

This executes when the Browser is Internet Internet Explorer.Explorer.This executes when the Browser is NOTNOT Internet Explorer. There are many ways and 3rd-party libraries that address the problem of different browser implementations.

AJAX: A Special Request Object Is Created

Page 17: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:A JavaScript

Function is Called

Page 18: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A JavaScript Function is Called

• AJAX is a driven by event logicevent logic. You ask AJAX to do something and that triggers an triggers an eventevent.

• If you want the event to be triggered right away when your web page has finished loading, then you can use the routine <body onload=“javascript; myEvent();”> style.

• If you want the event to be triggered by a specific event that happens after the page has been loaded and the user does something, then you can use any of the traditional JavaScript events such as onClick(), onBlur(), etc.

Page 19: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A JavaScript Function is Called

• After the page has loaded, we have the opportunity to press a button—not even a submit button—and trigger an onClick event.

Page 20: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A JavaScript Function is Called• By the time the user has pressed the button that causes sendRequest() to be executed, the http variable has been created with a request object appropriate for the browser.

When this function gets executed, we open a connection to our servlet using the GET.

Page 21: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A JavaScript Function is Called• The second statement in this function– http.onreadystatechange–is where we assign the callback handlercallback handler, which is the method that will handle the responses that will come back asynchronously

When this function gets executed, we open a connection to our servlet using the GET.

/AJAXProject/servlet/freejavalectures.AJAXServlet

AJAXProject = the Context Root of my web

application

freejavalectures = the package where my servlet is

located

Page 22: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: A JavaScript Function is Called• The second statement in this function– http.onreadystatechange –is where we assign the callback handler, which is the method that will handle the responses that will come back asynchronously

The second line is a bit of JavaScript trickery. handleResponse is actually a JavaScript functionfunction. JavaScript allows us to assign a function like this event handlerevent handler without using the open and close parenthesis ()() we expect to see as part of a function name.

Page 23: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:An Asynchronous Request is Sent

Page 24: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: An Asynchronous Request is Sent• The second statement in this function– http.onreadystatechange –is where we assign the callback handler, which is the method that will handle the responses that will come back asynchronously

Finally, we execute the send(). Notice the null argument. In this example we are simply sending a GET to the named Servlet. We are not not sending any parameterssending any parameters in this request. If we had been sending parameters, they would be mentioned in the send().Understand—this is an AsynchronousAsynchronous request. After we execute the send, our ‘sendRequest()’ function will immediately returnimmediately return but that does not mean our results are ready.

Page 25: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: An Asynchronous Request is Sent• As we saw from the previous slide, our request is sent—in this example—to a servlet.

• Notice how we return our data—we are just just writing to thewriting to the HttpServletResponse’s output output streamstream. Simple.

In this example, we’re writing HTML. In other cases, it could be text/xml.

We also need to avoid having the browser cache these results.

We build the HTML we want to send here.

Page 26: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:The Response

Eventually Comes

Page 27: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: The Response Eventually Comes• One of the puzzling aspects of AJAX is the response. We will not get just one responsewill not get just one response—but many.

• First we will get a response that says: “I’m working on it.”

• Then we will get a response that says: “I’m loading.”

• Then, “I’m finished loading.”• Finally, after several unimportant several unimportant

intermediateintermediate responses responses, we get the one we were originally seeking.

Page 28: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: The Response Eventually Comes• In this example, we disregard any readyState value other than 4,which means our response data is ready.

The responseText is merely whatever was written to the Servlet output stream. There are alternatives to this, such as:http.reponseXML that allows you to send structured data back.

Page 29: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: The Response Eventually Comes• In this example, we disregard any readyState value other than 4,which means our response data is ready. Next, we get the

HTML element from something called the DOMDOM by its id. In this case, the place where we want is called content.

See—here on our HTML page—where the id is assigned. Without reloading the page, we will modify the existing HTML.

Page 30: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOM?

Page 31: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?

• When we think of a webpage, we consider its HTML structureHTML structure, right?

• If we’re more advanced, we think of the CSS stylesCSS styles that give it its look at feel.

• Well, in the eyes of JavaScriptJavaScript, a webpage is a tree of structure known as the DOM or

Document Object ModelDocument Object Model.

• JavaScript views a webpage as objects with objects with propertiesproperties that can be manipulated using the DOM

Page 32: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?

• The DOM is a treetree structure structure of objects on a webpage that can be addressed using JavaScript to change the appearancechange the appearance or even the underlying HTMLunderlying HTML of an existing page.

Page 33: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?

• This is a basic HTML page—the HTML HTML structurestructure at least.

<html> <head> <title>Basic HTML</title> </head> <body> <table> <tr> <td> First:<input type=“text” name=“first”/> </td> <td> Last:<input type=“text” name=“last” /> </td> </tr> </table> </body></html>

Page 34: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?• Normally, it’s hard to see the DOM

underlying a webpage but the Firefox browser comes with a neat tool that helps us see the actual DOM that was created for this page.

Page 35: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?• This is the DOM that Firefox created for our

page.This is a treetree, composed of several tree nodestree nodes.

This must be a perfect tree structure, so sometimes extra nodes—such as TBODY—get added to fill out the structure.

As you can see, it should be possible for us to navigate our way down to the document root (from a place called window.document) to anyplace in the document we need to be.

Page 36: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?• You can navigate your way through this

DOM tree but most times we have a better way.

• We assign a unique id to any element we want to access.

• Any piece of HTML can have an id.<html> <head> <title>Basic HTML</title> </head> <body> <table> <tr> <td id="firstTD"> First:<input type=“text” name=“first”/> </td> <td> Last:<input type=“text” name=“last” onMouseOver="changeFirstInput();"/> </td> </tr> </table> </body></html>

Page 37: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

Looking at the corresponding DOM tree in Firefox, we see that our ID is associated with the TD. By using some simple JavaScript, we can access that HTML node and change the HTML at that node without reloading or otherwise changing the page.

What is the DOMDOM?

Page 38: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

What is the DOMDOM?• Then, in a JavaScript <script> block, we can

get a handle on that id-identified element and work with it.

<html> <head> <title>Basic HTML</title> <script type="text/javascript"> function changeFirstInput() { var fTD = document.getElementById( "firstTD" ); fTD.innerHTML = "<b>First</b><input type='button' name='changed' value='Changed'/>"; } </script> </head> <body> <table> <tr> <td id="firstTD"> First:<input type=“text” name=“first”/> </td> <td> Last:<input type=“text” name=“last” onMouseOver="changeFirstInput();"/> </td> </tr> </table> </body></html>

So, we grab that HTML node and use a cool feature called innerHTML to change the HTML within that node.

Page 39: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:The HTML of the page is changed.

Page 40: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: The HTML of the page is changed.

• So, following our onMouseOver event, our original HTML is changed into something else.

Page 41: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:An Elaboration of

the Process

Page 42: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: An Elaboration of the Process.

• So far, we have seen an end-to-end exampleend-to-end example of an AJAX call.

• From what has already been seen, you can do a complete AJAX request-response cycle.

• But AJAX has a lot more complexity that we have omitted.

For example:• What happens if an error occurrederror occurred?

Page 43: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: An Elaboration of the Process.

• Although the request may1 have a readyState == 4, that does does notnot guarantee guarantee everything workedeverything worked as intended.

• To see if the request was successful, we need to look at the status. If the status == 200, then we know it worked.

1Thanks for technical assistance from Kate Keeley

Page 44: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: An Elaboration of the Process.

• If you recall a few slides back, we built HTML within our Servlet. Before we did a write() to the request object, we set the request.setContentType( “text/html” );

• In fact, it is more commonmore common to set the content type = text/xml.

• Therefore, ifif you set the content type to text/xml, you need to actuallyactually write XML.

Page 45: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX:Returning XML

Page 46: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• If you want to return more than one piece of data using a single AJAX call, then you need to:

create XML, signal that what you’re returning is

XML consume the XML correctly on your

page.

Page 47: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• In this example, we’re trying to bring back more than one item.• We start with the typical AJAX code to get started.

Page 48: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• This is the Servlet that gets called.

Notice that we set the content type to be “text/xml”.

This method just gets the parameters from the request and places them in an object called StoreWeb

This method queries the database based on the parameters.

This method takes the data we just got from the database and takes it from the Vendor object and creates a String XML file.

Finally, this statement just writes the String that contains the XML to the PrintWriter output.

Page 49: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• This is the method that builds the XML.

This is a very simple method. We just grab the fields and use them to build XML. Dang simple.

Page 50: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• The XML is created as a String and that’s written to the output stream.

This is the rest of the method.

Then the XML is written.

Page 51: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• Back on the JSP where the original AJAX call was made, here is the code that consumes the XML we just wrote.

This is the first case where we are reading the XML. Notice how this is accomplished. The original XML had a node called SOURCE_NUM. This allows us to get the data that was between <SOURCE_NUM>xxx</SOURCE_NUM>

from the original XML

Page 52: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML• Sometimes it’s not as easy as that. For example, if I wanted to recreate an HTML SELECT statement using AJAX, I would prefer to send down XML.• This is the XML I’m sending down from my Servlet.

<?xml version="1.0" encoding="ISO-8859-1"?>

<SELECT>

<OPTION>

<VALUE>0</VALUE>

<CAPTION>-- Select --</CAPTION>

</OPTION>

<OPTION>

<VALUE>1</VALUE>

<CAPTION>My First Dropdown Caption</CAPTION>

</OPTION>

<OPTION>

<VALUE>2</VALUE>

<CAPTION>My Second Dropdown Caption</CAPTION>

</OPTION>

</SELECT>

Page 53: Asynchronous JavaSript and XML

Java III--Copyright © 2007 Tom Hunter

AJAX: Returning XML

• So, you sometimes need to use responseText and, on the fly, convert it into XML. This works in IE.

Notice that I reverted to

responseText

[ i ]