[英]AJAX POST request to a PHP server: Invalid request (Malformed HTTP request) on console and net::ERR_EMPTY_RESPONSE on chrome dev tools
I have the files test.html
, test.js
and test.php
in my directory.我的目录中有文件
test.html
、 test.js
和test.php
。 I am trying to send some data to my backend, which should be dealt with by test.php
.我正在尝试将一些数据发送到我的后端,这应该由
test.php
处理。 I run my server using PHP's built-in webserver with the command php -S 0.0.0.0:8080 -t test-server/
.我使用 PHP 的内置网络服务器运行我的服务器,命令
php -S 0.0.0.0:8080 -t test-server/
。
Here's a simplified demonstration, whenever I click "submit", it should send the data to my php server.这是一个简化的演示,每当我点击“提交”时,它应该将数据发送到我的 php 服务器。 The JS:
脚本:
window.onload = () => {
submit = document.getElementById('submit');
submit.addEventListener('click', () => {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
window.location.replace("test.php");
}
xhttp.open("test.php", "POST", true);
xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8');
var data = {'name':'foo'};
xhttp.send(JSON.stringify(data));
});
}
And here's my PHP:这是我的 PHP:
<?php
echo "foo";
var_dump($_POST);
?>
However, the data isn't being sent, and the xhttp.onload
never works.但是,数据没有被发送,并且
xhttp.onload
永远不会工作。 The error Invalid request (Malformed HTTP request)
shows up on my server and the error net::ERR_EMPTY_RESPONSE
pops up in chrome's developer tools.错误
Invalid request (Malformed HTTP request)
出现在我的服务器上,错误net::ERR_EMPTY_RESPONSE
弹出在 chrome 的开发人员工具中。
What am I doing wrong?我究竟做错了什么?
The xhttp.open uses this signature: xhttp.open 使用这个签名:
open(method, url, async, user, password)
You just inversed method and url in your call.您只是在调用中反转了方法和 url。
More informations: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open更多信息: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.