HTML and CSS Reference
In-Depth Information
• We specify that the data type returned will be json. This is used by jQuery to determine
how to parse the result. jQuery does a good job guessing this if it is omitted, so it is not
generally necessary to specify it. Other accepted values are xml, script, or html.
• Next we specify the URL of the resource we are accessing: this can be an absolute URL
as shown here or a relative URL. This does not specify the host and port of the server, since
the single-origin policy specifies that this must be the host and port of the document loaded
into the browser.
• We indicate that we do not want the browser to cache the result. jQuery will ensure the
resource is not cached by appending the current timestamp to the request, exactly as we
saw earlier when dynamically loading JavaScript scripts. This is a useful feature, since it is
generally not desirable to cache requests for data.
• A callback is provided for success scenarios. This will be called asynchronously when the
HTTP response is received, and passed the data received from the request.
jQuery offers a set of shorthand methods that reduce the code required still further. We have
already come across these for requesting JavaScript scripts from the server. For instance,
the example above could be written as follows:
$.getJSON( "/server/tasks.json", function( data ) {
console.log(data);
});
Due to the fact we are using the JSON data format, the data object passed to the callback
function will be a JavaScript object, automatically de-serialized from the data received. In
this case the object is an array containing four task objects. There is therefore no need to
transform the result into a format applicable to our application.
Before continuing, it is worth noting that as of jQuery 1.5 there is a better way to register
callbacks using a technique called “promises”.
The call to $.ajax actually synchronously returns a type of object called a “promise”. Any
asynchronous (or potentially asynchronous) API can utilize jQuery promises, and they are
widely used both within jQuery and beyond.
If you inspect this object in the debugger it looks like this:
Search WWH ::




Custom Search