如何使用getAllResponseHeaders方法制作JSON对象 [英] How to make a JSON object out of getAllResponseHeaders method

查看:489
本文介绍了如何使用getAllResponseHeaders方法制作JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在编写google chrome扩展程序,我需要查找有关网站响应标题的信息.为了做到这一点,我使用了getAllResponseHeaders方法,但是我需要将其放在JSON对象中.不幸的是,我一直收到错误消息SyntaxError: Unexpected token D in JSON at position 0 at main.

I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the getAllResponseHeaders method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message SyntaxError: Unexpected token D in JSON at position 0 at main.

这是到目前为止我正在使用的代码:

Here is the code I am using to do this so far:

xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        allResponseHeaders = xmlhttp.getAllResponseHeaders();
    }
};
xmlhttp.send();

var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;

当我在allResponseHeaders = xmlhttp.getAllResponseHeaders();呼叫后立即发出警报时,警报显示呼叫成功.响应头已全部检索到.第一个响应头是日期,我认为这与错误消息的Unexpected token D部分有关,但是我不知道为什么它无法正确解析.我该如何解决?预先感谢.

When I put an alert immediately after the allResponseHeaders = xmlhttp.getAllResponseHeaders(); call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the Unexpected token D part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.

我希望我的JSON对象看起来像这样:

I would like my JSON object to look something like this:

{
  "headers": {
    "Date": "June 20, 2016",
    "Content-Type": "charset=UTF/8",
    ...
  }
}

推荐答案

请参见 https://msdn.microsoft.com/en-us/library/ms536428(v = vs.85).aspx .返回标头是用crlf分隔的字符串,其中每行包含用冒号分隔的键值.您可能必须调整以下代码以解决空格问题.

See https://msdn.microsoft.com/en-us/library/ms536428(v=vs.85).aspx. The return headers are a crlf delimited string where each line contains key values separated by a colon. You will probably have to adjust the code below to account for whitespace.

var arr = allResponseHeaders.split('\r\n');
var headers = arr.reduce(function (acc, current, i){
      var parts = current.split(': ');
      acc[parts[0]] = parts[1];
      return acc;
}, {});

这篇关于如何使用getAllResponseHeaders方法制作JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆