为了账号安全,请及时绑定邮箱和手机立即绑定

在PHP中处理json请求

在PHP中处理json请求

PHP
慕娘9325324 2019-11-20 14:13:47
进行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) {}});
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

<?php

   var_dump(json_decode(file_get_contents('php://input')));

?>


查看完整回答
反对 回复 2019-11-20
?
精慕HU

TA贡献1845条经验 获得超8个赞

上面从技术上讲是正确的,但是由于我没有写太多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) {

    $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


查看完整回答
反对 回复 2019-11-20
  • 3 回答
  • 0 关注
  • 486 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信