在PHP中处理json请求

进行Ajax调用时,将contentType设置为application / json而不是默认的x-www-form-urlencoded时,服务器端(在PHP中)无法获取post参数。

在以下工作示例中,如果我在ajax请求中将contentType设置为“ application / json”,则PHP $ _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) {}

});


慕娘9325324
浏览 493回答 3
3回答

拉莫斯之舞

<?php&nbsp; &nbsp;var_dump(json_decode(file_get_contents('php://input')));?>

精慕HU

上面从技术上讲是正确的,但是由于我没有写太多PHP,所以这可能会更有帮助xxx.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) {&nbsp; &nbsp; $message = $key . ":" . $value . "\n";&nbsp; &nbsp; echo fwrite($file,$message);}fclose($file);?>然后你可以用curl -X POST -H "Content-Type: application/json" -d '{"fieldA":"xyz","fieldN":"xyz"}' http://localhost/xxx.php
打开App,查看更多内容
随时随地看视频慕课网APP