在PHP中处理json请求

在PHP中处理json请求,php,ajax,json,request,mime-types,Php,Ajax,Json,Request,Mime Types,进行ajax调用时,当contentType设置为application/json而不是默认的x-www-form-urlencoded时,服务器端(在PHP中)无法获取post参数。 在下面的工作示例中,如果我在ajax请求中将contentType设置为“application/json”,PHP$\u POST将为空。为什么会发生这种情况?如何在PHP中正确处理contentType为application/json的请求 $.ajax({ cache: false, ty

进行ajax调用时,当contentType设置为application/json而不是默认的x-www-form-urlencoded时,服务器端(在PHP中)无法获取post参数。
在下面的工作示例中,如果我在ajax请求中将contentType设置为“application/json”,PHP$\u POST将为空。为什么会发生这种情况?如何在PHP中正确处理contentType为application/json的请求

$.ajax({
    cache: false,
    type: "POST",
    url: "xxx.php",
    //contentType: "application/json",
    processData: true,
    data: {my_params:123},
    success: function(res) {},
    complete: function(XMLHttpRequest, text_status) {}
});

您将在
$HTTP\u RAW\u POST\u DATA
中找到无法识别的MIME类型。您还可以通过将PHP.ini指令
always\u populate\u raw\u post\u data
设置为true,强制PHP始终填充此数组(不仅仅针对无法识别的MIME类型)

原始post数据将通过输入包装器
php://input

有关更多信息:


以上在技术上是正确的,但由于我不太会编写PHP,这可能会更有帮助

php将是

<?php
$file = fopen("test.txt","a");
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
foreach($post as $key=>$value) {
    $message = $key . ":" . $value . "\n";
    echo fwrite($file,$message);
}
fclose($file);
?>

如果您有phalcon扩展,那么可以使用
getJsonRawBody()

<?php
$file = fopen("test.txt","a");
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
foreach($post as $key=>$value) {
    $message = $key . ":" . $value . "\n";
    echo fwrite($file,$message);
}
fclose($file);
?>
curl -X POST -H "Content-Type: application/json" -d '{"fieldA":"xyz","fieldN":"xyz"}' http://localhost/xxx.php