/* *************** */
/* Using fetch API */
/* *************** */
fetch('https://jsonplaceholder.typicode.com/comments/3')
.then(function(response){ // server response as a stream
return response.json(); // parse text using fetch json() method
})
.then(function(myObj){ // parsed object passed as argument so something can done with data
console.log("Fetch:", myObj.email); // do something with data
});
/* *************************** */
/* XmlHttpRequest (XHR) method */
/* *************************** */
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
let myObj = JSON.parse(xhr.responseText); // get the response data as a string but immediately parse into an object
console.log("XHR:", myObj.email);
}
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/comments/3');
xhr.send();
/* *********** */
/* jQuery Ajax */
/* *********** */
$.ajax({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/comments/3',
cache: false // do not cache the result
}).done(function(myObj){ // response data from request
console.log("Ajax:", myObj.email); // so something with the data
});