[英]Receive Json post and convert it to PHP variable
我正在嘗試將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的值,它只是空白。 我的代碼有什么問題,您可以幫我嗎?
嘗試使用此代碼,我已從請求代碼中刪除了數據類型。
var aksi='';
var jdata= JSON.stringify({
"code":"02",
"accountNo":"5503722012345678",
"amount":200,
"transDate":"20190109161439",
"traceNo":"1234567890",
"signature":"08CA625868C1E6FFC00D89EA7B668BD7"
});
$.ajax({
url:"http://localhost/stackoverflow.php",
type:"POST",
data:jdata,
contentType: "application/json",
success:function(resp){
// Check the values in console
console.log("kk");
},
failure: function(errMsg) {
alert(errMsg);
}
});
我也將代碼放在腳本標簽中,請也檢查一下
<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:"http://localhost/stackoverflow.php",
type:"POST",
data:jdata,
contentType: "application/json",
success:function(resp){
// Check the values in console
console.log("kk");
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.