530 likes | 680 Views
Java III. AJAX A synchronous J avaScript A nd X ML. AJAX: Introduction. AJAX: Introduction *. • AJAX is a term coined by Mr. Jesse James Garrett of Adaptive Path to describe a type of web programming that transfers information to and from the server without doing
E N D
AJAX Asynchronous JavaScript And XML
AJAX: Introduction
AJAX: Introduction* • AJAX is a term coined by Mr. Jesse James 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 technology, rather it is a clever combination of somewhat 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. Jesse James Garrett
AJAX: Introduction* • AJAX is a large topic that could fill hundreds of slides. • In this lecture, I intend only to present an introduction to AJAX. • This lecture will not be comprehensive. • This lecture will get you up and running with AJAX.
AJAX: A Quick Overview of How it Works
AJAX: A Quick Overview of How it Works • 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 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. 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 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. 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.
AJAX: A Quick Overview of How it Works 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. 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.
AJAX: A Quick Overview of How it Works 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. 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.
AJAX: A Quick Overview of How it Works 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. 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.
AJAX: A Special Request Object is Created
AJAX: A Special Request Object Is Created • When the page loads, 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.
AJAX: A Special Request Object Is Created • 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 Explorer. This executes when the Browser is NOT Internet Explorer. There are many ways and 3rd-party libraries that address the problem of different browser implementations.
AJAX: A JavaScript Function is Called
AJAX: A JavaScript Function is Called • AJAX is a driven by event logic. You ask AJAX to do something and that triggers an event. • 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.
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.
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.
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 When this function gets executed, we open a connection to our servlet using the GET. AJAXProject = the Context Root of my web application freejavalectures = the package where my servlet is located /AJAXProject/servlet/freejavalectures.AJAXServlet
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 function. JavaScript allows us to assign a function like this event handlerwithout using the open and close parenthesis () we expect to see as part of a function name.
AJAX: An Asynchronous Request is Sent
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 sending any parameters in this request. If we had been sending parameters, they would be mentioned in the send(). Understand—this is an Asynchronous request. After we execute the send, our ‘sendRequest()’ function will immediately return but that does not mean our results are ready.
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 writing to theHttpServletResponse’s output stream. 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.
AJAX: The Response Eventually Comes
AJAX: The Response Eventually Comes • One of the puzzling aspects of AJAX is the response. We will 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 intermediate responses, we get the one we were originally seeking.
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.
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 DOM 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.
What is the DOM? • When we think of a webpage, we consider its HTML structure, right? • If we’re more advanced, we think of the CSS styles that give it its look at feel. • Well, in the eyes of JavaScript, a webpage is a tree of structure known as the DOM or Document Object Model. • JavaScript views a webpage as objects with properties that can be manipulated using the DOM
What is the DOM? • The DOM is a tree structure of objects on a webpage that can be addressed using JavaScript to change the appearance or even the underlying HTML of an existing page.
What is the DOM? • This is a basic HTML page—the HTML structure 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>
What is the DOM? • 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.
What is the DOM? • This is the DOM that Firefox created for our page. This is a tree, composed of several tree 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.
What is the DOM? • 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>
What is the DOM? 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 DOM? • 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.
AJAX: The HTML of the page is changed.
AJAX: The HTML of the page is changed. • So, following our onMouseOver event, our original HTML is changed into something else.
AJAX: An Elaboration of the Process
AJAX: An Elaboration of the Process. • So far, we have seen an end-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 occurred?
AJAX: An Elaboration of the Process. • Although the request may1 have a readyState == 4, that does not guarantee everything 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
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 common to set the content type = text/xml. • Therefore, if you set the content type to text/xml, you need to actually write XML.
AJAX: Returning XML
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.
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.
AJAX: Returning XML Notice that we set the content type to be “text/xml”. • This is the Servlet that gets called. 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.
AJAX: Returning XML This is a very simple method. We just grab the fields and use them to build XML. Dang simple. • This is the method that builds the XML.
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.