最近我一直在使用fetch API和Promises,并遇到了.json()。很多时候.json()返回与JSON.parse相同的输出结果。我通过谷歌搜索了这个问题,但结果指向其他方向。
以下是XHR和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();
});
使用 Fetch API 的示例:
$('#fetch').click(function(){
fetch(url)
.then(function(res){
return res.json();
})
.then(function(quote){
$('#quote').text(quote);
})
.catch(function(err){
handleError(err);
});
});
有人能解释一下这些看似相似的概念的区别吗?谢谢。