Today, I want to share how to send HTTP request from browser using builtin JavaScript and jQuery.
XML HTTP Request (XHR)
var xhr = new XMLHttpRequest();
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/users/');
xhr.onreadystatechange = function() {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
for (var i = 0; i < users.length; ++i) {
console.table(users[i]);
}
} else {
console.error('There was a problem with the request. ' + users);
}
}
xhr.send();
The XMLHttpRequest.onreadystatechange
property contains the event handler to
be called when the readystatechange
event is fired, that is every time the
readyState
property of the XMLHttpRequest
changes.
XMLHttpRequest.onreadystatechange = /* callback */;
Property onreadystatechange
is supported in all browsers. Since then, a
number of additional event handlers have been implemented in various browsers
(onload
, onerror
, onprogress
, etc.).
Ready State | Num | Description |
---|---|---|
UNSENT |
0 | XHR constructed. |
OPENED |
1 | Method open() successfully invoked. |
HEADERS_RECEIVED |
2 | Redirection finished, all headers received. |
LOADING |
3 | The response’s body is being received. |
DONE |
4 | The data transfer has been completed, or error. |
jQuery 1.4
Load data from the server using a HTTP GET request.
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
with the following type table:
Key | Value |
---|---|
url | String |
data | PlainObject or String |
success | Function( PlainObject data, String textStatus, jqXHR jqXHR ) |
dataType | String |
For example:
$.ajax({
url: 'http://localhost:8080/users',
type: 'GET',
data: data,
success: function(users) {
for (var i = 0; i < users.length; ++i) {
console.table(users[i]);
}
},
error: function(xhr) {
var resp = JSON.parse(xhr.responseText);
console.table(resp);
}
});
jQuery 1.5+
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the
XMLHTTPRequest
object. This jQuery XHR object, or “jqXHR”, returned by
$.get()
implements the Promise
interface, giving it all the properties,
methods, and behavior of a Promise
.
MDN:
The
Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});