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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18973097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:54:42  来源:igfitidea点击:

Send HTTP request and receive HTTP response using javascript

javascripthttprequestresponse

提问by Sonia Sharma

I want to send HTTP request like a simple request for "http://google.com/" and then print the HTTP response headers on screen. How can it be done? I want the base code so that I can use it to send more complex GET and POST requests.

我想像对“ http://google.com/”的简单请求一样发送 HTTP 请求,然后在屏幕上打印 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>

This shows me an empty popup box.

这向我显示了一个空的弹出框。

回答by Vishal Goyal

You can't use XMLHttpRequest cross domain unless requested server explicitly allow it and google.com doesn't explicitly allow it. However you may disable the web security feature of your browser, and then your same code will start working.

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