Get raw HTTP response from AJAX

℡╲_俬逩灬. 提交于 2021-02-10 18:19:13

问题


Using plain JavaScript AJAX in a browser, can I get the raw HTTP response from the server?

By that I mean headers and body as raw text like:

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

(NB: I'm not talking about cross-origin requests)


回答1:


You will need to combine two calls to get the body and the response headers.

  • To get the headers, use getAllResponseHeaders
  • To get the body, use property .response when the readystate is 4 (=DONE)

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


来源:https://stackoverflow.com/questions/50677103/get-raw-http-response-from-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!