HTML and CSS Reference
In-Depth Information
We will now return to AJAX. So far we have examined AJAX GET requests. It is also pos-
sible to perform HTTP POSTs with AJAX. The most common use of this is to POST the
contents of a form to a server, but POST is flexible enough to allow any data structure to
be posted.
It is often more convenient to post structured data rather than raw form data. This is because
the server components will often be capable of de-serializing structured data (such as JSON
or XML) in to a rich hierarchy of objects, whereas form data consists of name/value pairs.
The following is an example of a function that sends a task object to the server, and returns
a promise to the caller:
function sendTask(task) {
return $.ajax({
type : "POST",
url : "/submittask",
contentType : "application/json",
data : JSON.stringify(task)
})
}
You will notice that we have set the content type to application/json . The default content
type is application/x-www-form-urlencoded , which is the appropriate content type for an
HTML form submission.
It is actually possible to simplify this code significantly with one of jQuery's shorthand
methods:
return $.post( "/submittask", task );
jQuery will infer the appropriate options, and implicitly stringify the task object provided.
There are a number of other options that can be provided when using the $.ajax() method.
Most of these are not required in most scenarios, but the following are worth knowing
about:
• async : AJAX calls do not have to be asynchronous (despite the “A” in AJAX). It is pos-
sible to perform synchronous AJAX calls by setting async to false . This is not recommen-
ded without a very good reason however, since the main browser thread will block until the
response is received.
• beforeSend : This is a pre-request callback that allows you to modify the request before it
is sent, for instance, adding specific headers to the request.
Search WWH ::




Custom Search