Recently, I've been diving into using fetch API and Promises, which led me to .json(). It's interesting how often .json() gives the same result as JSON.parse. After some initial confusion, I turned to Google for answers, only to be redirected in different directions.
Here is an example with XHR and JSON.parse:
$('#xhr').click(function(){
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function(){
if (XHR.status == 200 && XHR.readyState == 4) {
$('#quote').text(JSON.parse(XHR.responseText)[0]);
}
};
XHR.open("GET", url);
XHR.send();
});
And here is an example with Fetch API:
$('#fetch').click(function(){
fetch(url)
.then(function(res){
return res.json();
})
.then(function(quote){
$('#quote').text(quote);
})
.catch(function(err){
handleError(err);
});
});
I'm still confused though – can someone explain the distinction between these seemingly similar concepts? Thanks!