在使用 post 数据请求后,PHP 中的 $_POST 数组为空

$_POST array empty in PHP after an a request with post data

我正在使用此方法将参数发送到我的服务器 php 但我得到了您 post 发送的值:

function post(path, parameters) {
var http = new XMLHttpRequest();
console.log(parameters);
http.open("POST", path, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(parameters);
}

php :

public function tracking_referidos(){
    $this->autoRender = false;
    $result = array();
    $result['post'] = $_POST;
    echo json_encode($result);
    exit;
}

结果:{"post":{"referrer":"","event":"eventrid","hash":"45hfkabdus"}}

您正在发送 JSON 字符串。 PHP 不会解码该数据并将其自动映射到 $_POST 超级全局。如果您希望 PHP 这样做,您需要将数据作为 application/x-www-form-urlencoded 发送(即类似于 get 请求的 URI:key=value&key2=value2)。

您可以使用 application/json 内容类型发送数据,但要获取请求数据,您需要读取原始 post 正文。您可以在 php://input 流中找到它。只需使用file_get_contents阅读即可:

$rawPostBody = file_get_contents('php://input');
$postData = json_decode($rawPostBody, true);//$postData is now an array