从AJAX获取原始HTTP响应

时间:2018-06-04 09:13:29

标签: javascript ajax

在浏览器中使用纯JavaScript AJAX,我可以从服务器获取原始 HTTP响应吗?

我的意思是标题和正文作为原始文本,如:

< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.co.uk/
< Content-Type: text/html; charset=UTF-8
< Server: gws
< Content-Length: 221
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Age: 11
< Date: Mon, 04 Jun 2018 09:12:14 GMT
< Expires: Wed, 04 Jul 2018 09:12:14 GMT
< Cache-Control: public, max-age=2592000
< Connection: keep-alive
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>

(注意:我不是在谈论跨源请求)

1 个答案:

答案 0 :(得分:1)

您需要组合两个调用来获取正文和响应标题。

var request = new XMLHttpRequest();
request.open("GET", "http://www.example.com", true);
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4){
    console.log(request.getAllResponseHeaders());
    console.log(request.responseText);
  }
};