cha*_*nux 83 javascript json firefox-addon bit.ly
我试图在javscript中解析一点JSON响应.
我通过XmlHttpRequest获取JSON.
var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url)
+ BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);
parseJSON: function(req, url) {
if (req.status == 200) {
var jsonResponse = req.responseJSON;
var bitlyUrl = jsonResponse.results[url].shortUrl;
}
Run Code Online (Sandbox Code Playgroud)
我在firefox插件中执行此操作.当我运行时,我得到错误"jsonResponse is undefined" var bitlyUrl = jsonResponse.results[url].shortUrl;
.我在这里解析JSON有什么不妥吗?或者这段代码有什么问题?
Tor*_*ben 207
新方式我: fetch
TL; DR我建议这样,只要您不必发送同步请求或支持旧浏览器.
只要您的请求是异步的,您就可以使用Fetch API发送HTTP请求.fetch API与promises一起使用,这是一种在JavaScript中处理异步工作流的好方法.使用此方法,您可以使用fetch()
发送请求并ResponseBody.json()
解析响应:
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// do something with jsonResponse
});
Run Code Online (Sandbox Code Playgroud)
兼容性:IE11以及Edge 12和13不支持Fetch API.但是,有polyfill.
新方式II: responseType
正如Londeren在他的回答中所写,较新的浏览器允许您使用该responseType
属性来定义响应的预期格式.然后可以通过response
属性访问已解析的响应数据:
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = req.response;
// do something with jsonResponse
};
req.send(null);
Run Code Online (Sandbox Code Playgroud)
兼容性:responseType = 'json'
IE11不支持.
经典的方式
标准XMLHttpRequest没有responseJSON
属性,只是responseText
和responseXML
.只要你的请求中有一些JSON响应,就responseText
应该包含JSON代码作为文本,所以你要做的就是解析它JSON.parse()
:
var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = JSON.parse(req.responseText);
// do something with jsonResponse
};
req.send(null);
Run Code Online (Sandbox Code Playgroud)
兼容性:此方法适用于任何支持XMLHttpRequest
和的浏览器JSON
.
JSONHttpRequest
如果您更喜欢使用responseJSON
,但想要比JQuery更轻量级的解决方案,您可能需要查看我的JSONHttpRequest.它的工作方式与普通的XMLHttpRequest完全相同,但也提供了responseJSON
属性.您需要在代码中更改所有内容的第一行:
var req = new JSONHttpRequest();
Run Code Online (Sandbox Code Playgroud)
JSONHttpRequest还提供了将JavaScript对象轻松发送为JSON的功能.更多细节和代码可以在这里找到:http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.
完全披露:我是Pixels | Bytes的所有者.我认为我的脚本是解决问题的好方法,所以我在这里发布了.如果您要我删除链接,请发表评论.
Lon*_*ren 17
你可以简单地设置 xhr.responseType = 'json';
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
console.log('response', this.response); // JSON response
}
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)