JSON.parse() 比。 .json()
JSON.parse() Vs. .json()
我最近一直在使用 fetch API 和 Promises,我遇到了 .json() 。通常 .json() returns 与 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);
});
});
有人可以解释一下这些看似相似的概念之间的区别吗?
谢谢
Body.json()
is asynchronous and returns a Promise
object that resolves to a JavaScript object. JSON.parse()
是同步的可以解析一个字符串并改变结果返回的 JavaScript 对象。
在我看来,res.json 和 JSON.parse 的功能相同。优先使用 res.json 是因为它的语法。
分享示例以更好地理解...
this.service.userFunction() //calling service
.then((res) => {
this.userdetails = JSON.parse(res._body); //use this
this.userdetails = res.json(); // or use this syntax any one
)}
.catch()
使用其中任何一个都将提供完整的响应主体和对其功能的理解。
'AJAX' 适用于 'callbacks';
'fetch' 适用于 'promises'。
使用 JSON.parse() 解析 AJAX 的响应。
使用 json() 解析获取响应。
Body mixin 的 json() 方法采用 Response 流并将其读取完成。它 returns 一个以将正文解析为 JSON 的结果解析的承诺。
JSON.parse() 方法解析 JSON 字符串 ,构造字符串描述的 JavaScript 值或对象。
使用 JSON.parse() 解析 AJAX 的响应。使用 json() 解析获取响应。
我最近一直在使用 fetch API 和 Promises,我遇到了 .json() 。通常 .json() returns 与 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);
});
});
有人可以解释一下这些看似相似的概念之间的区别吗? 谢谢
Body.json()
is asynchronous and returns a Promise
object that resolves to a JavaScript object. JSON.parse()
是同步的可以解析一个字符串并改变结果返回的 JavaScript 对象。
在我看来,res.json 和 JSON.parse 的功能相同。优先使用 res.json 是因为它的语法。 分享示例以更好地理解...
this.service.userFunction() //calling service
.then((res) => {
this.userdetails = JSON.parse(res._body); //use this
this.userdetails = res.json(); // or use this syntax any one
)}
.catch()
使用其中任何一个都将提供完整的响应主体和对其功能的理解。
'AJAX' 适用于 'callbacks'; 'fetch' 适用于 'promises'。
使用 JSON.parse() 解析 AJAX 的响应。 使用 json() 解析获取响应。
Body mixin 的 json() 方法采用 Response 流并将其读取完成。它 returns 一个以将正文解析为 JSON 的结果解析的承诺。 JSON.parse() 方法解析 JSON 字符串 ,构造字符串描述的 JavaScript 值或对象。
使用 JSON.parse() 解析 AJAX 的响应。使用 json() 解析获取响应。