Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

CHAPTER 14: Using Ajax: Part I > Using the Type-Specific Convenience Methods - Pg. 421

CHAPTER 14 USING AJAX: PART I The issue here is that the statements in the script element are not executed in the order in which they are written. The problem is that I have assumed that the following sequence will occur: 1. 2. 3. Define the elems variable. Get the data from the server and assign it to the elems variable. Slice the elements in the elems variable and add them to the document. What really happens is this: 1. 2. 3. Define the elems variable. Start the asynchronous request to the server. Slice the elements in the elems variable and add them to the document. And, at some point in the near future, this happens: 1. 2. Receive the request from the server. Process the data and assign it to the elems variable. In short, you get the error message because you called the slice methods on a variable that doesn't contain any elements. The worst thing about this mistake is that sometimes the code actually works. This is because the Ajax response completes so quickly that the variable contains the data you expect before you come to process it (this is typically the case when the data is cached by the browser or you perform some complex operations between starting the Ajax request and trying to operate on the data). You now know what to look for whether you see this kind of behavior from your code. Using the Type-Specific Convenience Methods jQuery provides three convenience methods that make dealing with particular types of data a little more convenient. These methods are described and demonstrated in the sections that follow. Getting an HTML Fragment The load method will only obtain HTML data, which allows you to request an HTML fragment, process the response to create a set of elements, and insert those elements in the document in a single step. Listing 14-15 shows how you can use the load method. Listing 14-15. Using the Load Shorthand Method ... <script type="text/javascript"> $(document).ready(function() { $('<button>Ajax</button>').appendTo('#buttonDiv').click(function(e) { $('#row1').load("flowers.html"); e.preventDefault(); 391