我正在尝试在 javascript 中解析一个 bit.ly 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;
}
我在 Firefox 插件中执行此操作。当我运行时,var bitlyUrl = jsonResponse.results[url].shortUrl;
行出现错误“jsonResponse is undefined”。我在这里解析 JSON 有什么问题吗?或者这段代码有什么问题?
最佳答案
我的新方法:fetch
TL;DR只要您不必发送同步请求或支持旧浏览器,我会推荐这种方式。
只要您的请求是异步的,您就可以使用 Fetch API发送 HTTP 请求。提取 API 与 promises 一起使用,这是在 JavaScript 中处理异步工作流的好方法。使用这种方法,您可以使用 fetch()
发送请求并使用 ResponseBody.json()
来解析响应:
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// do something with jsonResponse
});
兼容性:IE11 以及 Edge 12 和 13 不支持 Fetch API。但是,有 polyfills .
新方式二:responseType
作为 Londeren写在 his answer ,较新的浏览器允许您使用 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);
兼容性:responseType = 'json'
不受 IE11 支持。
经典方式
标准的 XMLHttpRequest 没有 responseJSON
属性,只有 responseText
和 responseXML
。只要 bitly 真的用一些 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);
兼容性:这种方法应该适用于任何支持 XMLHttpRequest
和 JSON
的浏览器。
JSONHttpRequest
如果您更喜欢使用 responseJSON
,但想要一个比 JQuery 更轻量级的解决方案,您可能需要查看我的 JSONHttpRequest。它的工作方式与普通的 XMLHttpRequest 完全相同,但还提供了 responseJSON
属性。您只需更改代码中的第一行即可:
var req = new JSONHttpRequest();
JSONHttpRequest 还提供了以 JSON 格式轻松发送 JavaScript 对象的功能。更多细节和代码可以在这里找到:http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/ .
完全披露:我是 Pixels|Bytes 的所有者。我认为我的脚本是原始问题的一个很好的解决方案,但今天它已经过时了。我不建议再使用它了。
关于javascript - 从 XmlHttpRequest.responseJSON 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1973140/