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 15: Using Ajax: Part II > Setting Up and Filtering Ajax Requests - Pg. 457

CHAPTER 15 USING AJAX: PART II } }); }); </script> ... In this example, I have registered a function for the text html type. Notice that you use a space between the components of the MIME type (as opposed to text/html). The function is passed the data that has been received from the server and returns the converted data. In this case, I simply pass the HTML fragment that is contained in the flowers.html file to the jQuery $ function and return the result. This means I can call all the usual jQuery methods on the object passed as the data argument to the success function. Tip The data types don't always match the MIME types that are returned by the server. For example, application/json is usually presented as "text json" to the converters method. It is easy to get carried away with these converters. I always try to avoid the temptation to do more in these functions than I should. For example, I am sometimes tempted to take JSON data, apply a data template, and pass the resulting HTML elements back. And although this is a nice trick, it can catch you out if someone else tries to extend your coding or you need to unwind heavy processing to get at the raw data later. Setting Up and Filtering Ajax Requests Now that you have seen the ajax method and the settings that are available, you can turn your attention to a couple of additional methods that jQuery provides to make configuring requests simpler. Defining Default Settings The ajaxSetup method lets you specify the settings that will be used for every Ajax request, freeing you from having to define all of the settings you are interested in for each and every request. Listing 15-21 shows this method in use. Listing 15-21. Using the ajaxSetup Method ... <script type="text/javascript"> $(document).ready(function() { $.ajaxSetup({ timeout: 15000, global: false, error: function(jqxhr, status, errorMsg) { $('<div class=error/>') 427