小编典典

从XmlHttpRequest.responseJSON解析JSON

json

我正在尝试在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插件中执行此操作。运行时,出现该行的错误“ jsonResponse is undefined” var bitlyUrl = jsonResponse.results[url].shortUrl;。我在这里解析JSON时做错什么了吗?还是这段代码有什么问题?


阅读 431

收藏
2020-07-27

共1个答案

小编典典

我的新方法: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
  });

兼容性:IE11以及Edge 12和13不支持Fetch API。但是,有
polyfills

新方法二: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);

兼容性: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);

兼容性:此方法应与支持XMLHttpRequest和的任何浏览器一起使用JSON

JSONHttpRequest

如果您喜欢使用responseJSON,但是想要一个比JQuery更轻巧的解决方案,则可能需要查看我的JSONHttpRequest。它的工作原理与普通的XMLHttpRequest完全相同,但也提供了该responseJSON属性。您只需要在代码中更改第一行即可:

var req = new JSONHttpRequest();

JSONHttpRequest还提供了轻松将JavaScript对象作为JSON发送的功能。更多详细信息和代码可以在这里找到:http : //pixelsvsbytes.com/2011/12/teach-your-
xmlhttprequest-some-json/。

全面披露:我是Pixels | Bytes的所有者。 我认为我的脚本可以很好地解决该问题,因此我将其发布在此处。如果您要我删除链接,请发表评论。

2020-07-27