前端ajax用json方式请求 后端php 用 $GLOBALS['HTTP_RAW_POST_DATA'] 取值
//参数-------------------------------------- var params = {}; params['module'] = "ai"; params['action'] = "nextAiNode"; params['apiVersion'] = "1.0"; params['userId'] = ""; params['sessionId'] = ""; params['token'] = ""; params['time'] = ""; params['callerId'] = "13977666666"; params['channelId'] = "1"; params['para'] = { "event":"sessionStart", "asrText":"" }; //请求------------------------------ $.ajax({ type: "POST", url: "../webApi.php", contentType: "application/json;charset=utf-8", data: JSON.stringify(params), dataType: "json", success:function (message) { //alert("提交成功"+JSON.stringify(message)); $("#div_msg").html(JSON.stringify(message)); }, error:function (message) { alert("提交失败"+JSON.stringify(message)); } });
注意: data: JSON.stringify(params), 中的 JSON.stringify() 方非常重要,如果没有则后端会取不到值。
php端
<?php //获得post的json数据, $postJson = json_decode($GLOBALS['HTTP_RAW_POST_DATA']); //获得event参数 $eventName=$postJson->para->event; $asrText=$postJson->para->asrText; $module=$postJson->module; $action=$postJson->action; $projectName=$postJson->projectName; $processName=$postJson->processName; $nodeName=$postJson->nodeName; $callerId=$postJson->callerId;
?>
在 PHP 中,$GLOBALS['HTTP_RAW_POST_DATA'] 已经 废弃(Deprecated),建议改用现代写法 php://input 来获取原始 POST 数据。
$jsonData = file_get_contents('php://input'); WriteLog($jsonData); $postJson = json_decode($jsonData, true); // true 返回数组,false 返回对象 if ($postJson === null) {
WriteLog("无效的 JSON 数据"); }else{ foreach ($postJson as $key => $value) { WriteLog("键: " . $key . ", 值: " . print_r($value, true) ); } } $bizId=$postJson['bizId'];//取值 $startDate=$postJson['startDate'];// $contacts=$postJson['contacts'] ;// WriteLog($bizId); WriteLog($postJson->startDate); WriteLog($postJson->contacts);

浙公网安备 33010602011771号