javascript - 从 XmlHttpRequest.responseJSON 解析 JSON

标签 javascript json firefox-addon bit.ly

我正在尝试在 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 属性,只有 responseTextresponseXML。只要 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);

兼容性:这种方法应该适用于任何支持 XMLHttpRequestJSON 的浏览器。

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/

相关文章:

javascript - 在 javascript 对象中创建函数的不同方法有什么区别?

javascript - 我可以通过 Javascript 在浏览器中设置本地时区吗?

javascript - Python 使用多个键对 JSON 对象进行分组

javascript - 尝试在我的 firefox 扩展中创建带有 svg src 的 iframe

javascript - 来自不同内容脚本和主要内容的 Firefox SDK 信息

javascript - Prettier vscode json文件缩进间距问题

javascript - 扩展 Google Maps API v3 类的最佳方式

php - array_udiff 返回不同的结果

android - JSON 从数据库中读取 4700 条记录

java - Selenium Webdriver (Java) 与 Firefox 扩展/插件连接/互操作