【发布时间】:2019-01-10 03:51:43
【问题描述】:
我正在尝试将 Json Post 转换/检索为 php 变量。 我有这个 payment.php 脚本
<script>
$(document).ready(function(){
$("#send").click(function(){
var aksi='';
var jdata= JSON.stringify({
"code":"02",
"accountNo":"5503722012345678",
"amount":200,
"transDate":"20190109161439",
"traceNo":"1234567890",
"signature":"08CA625868C1E6FFC00D89EA7B668BD7"
});
$.ajax({
url:"receive.php",
type:"POST",
data:jdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(resp){
// Check the values in console
console.log(resp);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
});
</script>
在receive.php上我有这个代码:
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
echo 'Request method must be POST!';
exit;
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
echo 'Content type must be: application/json';
exit;
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
echo 'Received content contained invalid JSON!';
exit;
}
//Sample php variable
$code = $decoded['code'];
echo $code;
但我在控制台上什么都没有,无论是错误消息还是 $code 的值,它都只是空白。 我的代码有什么问题,你能帮帮我吗?
【问题讨论】:
-
你不需要
stringify你的POST数据,你可以使用$_POST在receive.php中访问它——在下面查看我的答案。