[英]json_decode php returns null on valid json
我正在嘗試通過javascript中的ajax post發送一個json對象,如下所示:
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
cond 表示 json 對象,它是這樣的(用 JSON.stringify 轉換):
[{"field":"name","condition":"<","value":"John"}]
在 testPost.php 文件中,我有以下內容:
<?php
$return=$_POST["json"];
$decoded_json=json_decode($return);
$reply["json"]=$decoded_json;
print_r ( json_encode($reply));
?>
我的問題是 Json_decode 返回 null。
我檢查了編碼(UTF-8),還檢查了我發送到 php 文件的 json 女巫沒有斜線或任何東西。
誰能幫我?
您的Ajax數據已轉換為
[{json : {"field":"name","condition":"<","value":"John"}}]
由於json :
side而無效。
將您的Jquery轉換為
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {"json": cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
這里有一個作品示例,
<?php
if(count($_POST) > 0){
print_r($_POST);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
var cond = [{"field":"name","condition":"<","value":"John"}];
$.ajax({
type: 'POST',
url: 'a.php',
data: {"json" : cond},
dataType: 'text',
complete: function(response) {
$("body").html(response.responseText);
}
});
})
</script>
</head>
<body>
</body>
</html>
header('Content-Type: application/json');
您需要在回顯之前在PHP中添加此行。
然后
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response.field);
alert(response.condition);
alert(response.value);
}
});
嘗試使用 stripslashes() 然后 json_decode()
$decoded_json = json_decode(stripslashes($return));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.