带有发布数据的请求后,PHP 中的 $_POST 数组为空

NHT*_*res 1 javascript php post xmlhttprequest

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

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);
}
Run Code Online (Sandbox Code Playgroud)

php :

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

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

Eli*_*gem 6

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

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

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