JSON.parse() Vs. .json()(JSON.parse() 与..json())
问题描述
我最近一直在使用 fetch API 和 Promises,我遇到了 .json() ..json() 通常返回与 JSON.parse 相同的输出.我用谷歌搜索了这个问题,结果指向了其他方向.
I have been working with fetch API and Promises recently and I came across .json() . Oftentimes .json() returns the same output as JSON.parse. I googled the question and the results pointed in other directions.
XHR 和 JSON.parse 示例:
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();
});
Fetch API 示例:
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);
});
});
有人能解释一下这些看似相似的概念之间的区别吗?谢谢
Could someone please explain the difference between these seemingly similar concepts ? Thanks
推荐答案
Body.json()
是异步的,并返回一个解析为 JavaScript 对象的 Promise
对象.JSON.parse()
是同步的,可以解析一个字符串并改变结果返回的 JavaScript 对象.
Body.json()
is asynchronous and returns a Promise
object that resolves to a JavaScript object. JSON.parse()
is synchronous can parse a string and change the resulting returned JavaScript object.
这篇关于JSON.parse() 与..json()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JSON.parse() 与..json()


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01