我在试着分析一下.javascript中的JSON响应.

I get the JSON via XmlHttpRequest.

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;  
}

I do this in a firefox addon. When I run I get the error "jsonResponse is undefined" for the line var bitlyUrl = jsonResponse.results[url].shortUrl;. Am I doing anything wrong in parsing JSON here? Or what is wrong with this code?

推荐答案

New ways I: 100

100 I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: 100

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

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);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

标准的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);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

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

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

Json相关问答推荐

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

震击:三针并用震击

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

Spark-SQL中的from_unixtime函数未能给出正确的输出

遍历 JSON,检索父值

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

Powershell 7.2:ConvertFrom-Json - 日期处理

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

如何用 Xidel 正确读取这个 JSON 文件?

ASP.NET MVC - 将 Json 结果与 ViewResult 结合起来

如何一次加载无限滚动中的所有条目以解析python中的HTML

在 bash 中将 CSV 转换为 JSON

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

什么 Python 框架用于没有前端的 REST/JSON Web 服务?

JSON.stringify 不会转义?

PostgreSQL 中的 JSON 模式验证?

Spring restTemplate 获取原始 json 字符串

POST:在 url 本身中发送 post 请求

Javascript:如何判断 AJAX 响应是否为 JSON