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

时间:2018-07-10 16:33:57

标签: 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。这是对服务器的唯一请求。

为什么未设置$_POST['name']以及如何解决?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

在POST(MIME类型)时,有多种方法可以对数据进行编码。 PHP的$ _POST仅自动解码www-form-urlencoded

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)查看发生的情况。