这是我要发布到我的API的JavaScript代码:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
pageRequest.send("firstname=John&lastname=Doe");
这是我的PHP后端代码:
<?php
if (isset($_POST["firstname"]) && isset($_POST["lastname"])) {
$first_name = $_POST["firstname"];
$last_name = $_POST["lastname"];
echo "Hello, " . htmlspecialchars($first_name) . " " . htmlspecialchars($last_name);
} else {
echo "Please include all fields.";
}
?>
但是,我的PHP代码仅回显“请包括所有字段。”,当我尝试这样做时
var_dump($_POST);
它返回一个空数组。我在这里做错什么了吗?
谢谢。
答案 0 :(得分:2)
您可能缺少请求标头的设置:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
*** pageRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
pageRequest.send("firstname=John&lastname=Doe");