我无法将字符串从javascript正确发送到服务器

我无法将字符串从javascript正确发送到服务器,javascript,php,post,xmlhttprequest,Javascript,Php,Post,Xmlhttprequest,我正在尝试使用以下脚本向服务器发送字符串: var xhr = new XMLHttpRequest(); xhr.open('POST', 'execute.php', true); var data = 'name=John'; xhr.send(data); 但是,在服务器端,当执行execute.php时 isset($_POST['name']) 它返回false。这是对服务器的唯一请求 为什么没有设置$\u POST['name']以及如何修复它?在发送数据之前尝试设置请求头:

我正在尝试使用以下脚本向服务器发送字符串:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.send(data);
但是,在服务器端,当执行execute.php

isset($_POST['name']) 
它返回
false
。这是对服务器的唯一请求


为什么没有设置
$\u POST['name']
以及如何修复它?

在发送数据之前尝试设置请求头:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);

发布时,有多种方法对数据进行编码(MIME类型)。PHP的$\u POST只会自动解码www表单

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var data = 'name=John';   

xhr.send(data);
如果发送JSON编码的数据,则必须读取整个帖子正文,并自己对其进行JSON解码

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
var data = JSON.stringify({'name':'John'});

xhr.send(data);
在PHP中

$entityBody = file_get_contents('php://input');
$myPost = json_decode($entityBody);
$myPost['name'] == 'John';

使用浏览器的网络检查器(f12)查看发生了什么。

这里的
HMLHttpRequest
是打字错误,还是这样?是否应该是
XMLHttpRequest
?是的,很抱歉,我在原始代码中正确地使用了它。我认为您缺少一个请求头。。。try:xhr.setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);(在你发送数据之前)内容类型很好。这在我身上发生的次数太多了,它可能会触发$u POST变量的错误值。它成功了,谢谢!但它是否可能不适用于长字符串,如base64图像?它是否受到某种限制?@EricValls不必担心,您可以在php.ini文件中限制php_值post_max_大小。我在我的一台服务器上使用了512M的值,效果非常好。