使用javascript发送HTTP请求并接收HTTP响应

Son*_*rma 5 javascript http response request

我想发送HTTP请求,例如" http://google.com/ " 的简单请求,然后在屏幕上打印HTTP响应标头.怎么做到呢?我想要基本代码,以便我可以使用它来发送更复杂的GET和POST请求.

<html>
<body>

<script type="text/javascript">
function sendgetreq()
{
    var req = new XMLHttpRequest();
    req.open('GET', "https://www.google.com/search?q=asd", true);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    //document.write("Headers are:"+headers);
    alert(headers);
}
</script>
<INPUT TYPE=BUTTON OnClick="sendgetreq();" VALUE="Send Request">

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这显示了一个空的弹出框.

小智 0

您不能使用 XMLHttpRequest 跨域,除非请求的服务器明确允许它并且 google.com 没有明确允许它。但是,您可以禁用浏览器的网络安全功能,然后您的相同代码将开始工作。