Java Reference
In-Depth Information
Understanding the jQuery Function
The jQuery function ($()) is the doorway into all things jQuery, and you've used it quite a bit through-
out this chapter. However, there are other uses for this function. It was mentioned only once in this
book, and it was as an aside comment, but functions are objects, too. If you look back at the end of
Chapter 5, you created your own objects and reference types. When you did so, you used the prototype
object, which is a property of the Function object.
Just like all other objects, you access a Function object's properties and methods using the
object.property or object.method() syntax. As such, jQuery's Ajax functionality is provided by
methods of the $ function object. For example, to make a request to the server, you use the get()
method, as the following code shows:
$.get(“textFile.txt”);
This code makes a request to the server to retrieve the textFile.txt text fi le, but it isn't useful, as you
can't do anything with the data you retrieved. So like the HttpRequest module you built in the previous
chapter, the $.get() method lets you assign a callback function that is called when the request success-
fully contacts the server and retrieves your specifi ed data.
function get_callBack(data, status)
{
alert(data);
}
$.get(“textFile.txt”, get_callBack);
This code adds a function called get_callBack(), which jQuery calls on a successful request. When
jQuery executes an Ajax callback function, it passes two parameters to it. The fi rst, data, is the data you
requested from the server. The second, status, is the status of the request. Because jQuery only calls
the callback function on a successful request, status is always “success”.
Many developers forego using the second status parameter, because it's only possible value at this
time is success . You can forego it as well.
Using jQuery's Ajax Event Handling
jQuery's Ajax event handling is quite different from what you might expect. There are local events (that
is, events of a specifi c request object) and global Ajax events. Global events are easier to use, and you can
use them to add UI cues to enhance the user's experience. You set the global events to fi re on any valid
DOM object. One specifi c global event is the ajaxError event, and you set it to call an event handler
with the jQuery object's ajaxError() method, or you can use the bind() method. The following code
demonstrates the use of the ajaxError() method:
function request_ajaxError(event, request, settings)
{
alert(“An Ajax error occurred.”);
}
$(document).ajaxError(request_ajaxError);
Search WWH ::




Custom Search