2 ms·
What's more convenient $.getJSON('/my/url', function(data) { }); or var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onloa
by DeathArrow 4y ago
What's more convenient
$.getJSON('/my/url', function(data) {
});
or
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
?
- MaxLeiter 4y agoWhy not use fetch?
- divbzero 4y agoTo be fair with the comparison, we should add error handling for the jQuery example: $.getJSON('/my/url') .done(data => { // success }) .fail((jqxhr, textStatus) => { if (textStatus === 'timeout') { // connection error } else { // HTTP status error } }) And also consider the Fetch API alternative: fetch('/my/url') .then(response => { if (!response.ok) { // HTTP status error } return response.json() }) .then(data => { // success }) .catch(error => { // connection error })
- jefftk 4y agofetch('/my/url').then(response => response.json()).then(data => handle it)