jQuery in Action
Brushing up on Ajax
221
8.1.2 Initiating the request
Before we can send a request to the server, we need to do the following setup steps:
1
Specify the
HTTP
method such as (
POST
or
GET
)
2
Provide the
URL
of the server-side resource to be contacted
3
Let the
XHR
instance know how it can inform us of its progress
4
Provide any body content for
POST
requests
We set up the first two items by calling the
open()
method of
XHR
as follows:
xhr.open('GET','/some/resource/url');
Note that this method does not cause the request to be sent to the server. It merely
sets up the
sets up the
URL
and
HTTP
method to be used. The
open()
method can also be
passed a third Boolean parameter that specifies if the request is to be asynchro-
nous (if
nous (if
true
, which is the default) or synchronous (if
false
). There's seldom a
good reason not to make the request asynchronous (even if it means we don't have
to deal with callback functions); after all, the asynchronous nature of the request
is usually the whole point of making a request in this fashion.
to deal with callback functions); after all, the asynchronous nature of the request
is usually the whole point of making a request in this fashion.
Third, we provide a means for the
XHR
instance to tap us on the shoulder to
let us know what's going on; we accomplish this by assigning a callback function
to the
to the
onreadystatechange
property of the
XHR
object. This function, known as
the ready state handler, is invoked by the
XHR
instance at various stages of its pro-
cessing. By looking at the settings of the various other properties of
XHR
, we can
find out exactly what's going on with the request. We'll take a look at how a typical
ready state handler operates in the next section.
ready state handler operates in the next section.
The last steps to initiating the request are to provide any body content for
POST
requests and send it off to the server. Both of these are accomplished via the
send()
method. For
GET
requests, which typically have no body, no body content
parameter is passed as follows:
xhr.send(null);
When request parameters are passed to
POST
requests, the string passed to the
send()
method must be in the proper format (which we might think of as query
string format) in which the names and values must be properly
URI
-encoded.
URI
encoding is beyond the scope of this section (and as it turns out, jQuery is going
to handle all of that for us), but if you're curious, do a web search for the term
to handle all of that for us), but if you're curious, do a web search for the term
encodeURIComponent
, and you'll be suitably rewarded.