Send Request to Server
Ok, You have instantiated XHR object and created Ready State Handler
xhr.onreadystatechange = function () {...
.
The final step will be query resource from the server.
To do so, we need to set up the connection with OPEN method. :-
- Specify the HTTP method (usually POST or GET) and URL of the server resources.
- Send the request to server
xhr.open('GET', 'data1.html'); xhr.send(null);
It is as simple as what we see above.
The open method of XHR has FIVE arguments. There are open(method, url, async, user, password)
.
request method, request URL, , request username, and request password.
- method - Request Method ('GET' or 'POST')
- url - Request URL (in our case, it is just
data.html
. It can beverify?firstname=alex&lastname=david
) - async - synchronous flag (if unspecified, the value is default to true, which is asynchronous. In fact, asynchronous is usually our reason to query server resource in this manner)
- user - Request username
- password - Request passwod
By calling OPEN method, you have only set up the connection but you have yet send anything to server.
Since we are just getting data from server, a GET request, which typically have no body, no body content
parameter to send to server, we simply call send method with null argument send(null)
.
Note
By now, you have seen the simplest method to query or fetch data from web server. Let's move on to see something a little bit advance.