Java Reference
In-Depth Information
The send() method accepts any data that is to be sent with the request. If the request is a
GET request, this can be left empty because we are requesting data rather than sending it.
If the request is a POST request, the data can be sent in the form of a key=value query
string, like so:
Or a JSON string can be used:
Receiving the Response
Once the request has been sent, the program can continue doing some other task while it
waits for a response. Every time the the response status changes, the onreadystate-
change event will fire and the callback function that we set up earlier will be called. This
function can be used to process the response:
function processResponse() {
if (xhr.readyState === 4 && xhr.status === 200) {
// do something with the response
Inside the callback function, we check to see if the request has completed. When this hap-
pens, the readyState property will have a value of 4 and the HTTP status is 200 (in
other words, the request was okay). We can then place any code we want to run inside the
code block.
Note: No Callback is Needed if the Request is
Made Synchronously
A callback function is unnecessary if the request is made synchronously;
that is, by setting the third parameter of the open() method to false . The
code will pause after the send() method until the response is received, so
any code can simply be placed after the send() method.
Search WWH ::

Custom Search