将JavaScript对象传递给PHP无法正常工作
问题描述:
我正在尝试通过 JSON.stringify()
JavaScript:
Javascript:
$('#save').on('click touch', function(){
obj = {
"1" : {
"1" : "hey",
"2" : "hay"
},
"2" : {
"1" : "hey",
"2" : "hay"
}
}
var json = JSON.stringify( obj );
console.log(json)
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
ajax.php:
<?php
$obj = json_decode($json);
echo $obj;
?>
但是此代码返回一个错误,指出未定义 $ json
.我不知道为什么这不起作用.
But this code returns an error saying that $json
is not defined.
I have no idea why this is not working.
答
有2个问题.
- 您未随请求发送任何数据
- 这不是从PHP请求中获取值的方式
首先,添加此*:
$.ajax({
type: 'POST',
url: 'ajax.php',
data : { json: json }, // <---------------------
...
*这行得通,只是因为jQuery实现会自动将任何非字符串数据参数转换为采用表单编码的查询字符串.请参见文档.
然后,在您的PHP中,您应该这样做:
Then, in your PHP, you should do:
$jsonStr = $_POST['json'];
$json = json_decode($jsonStr);
另一种可能的方式:
Another possible way:
$.ajax({
type: 'POST',
url: 'ajax.php',
data : json , // <---------------------
...
这样,您的数据将不是有效的 form-urlencoded
输入,因此PHP不会将其解析为 $ _ POST
,但是您仍然可以获取其中的内容您的输入将执行以下操作:
This way, your data will not be a valid form-urlencoded
input, so PHP will not parse it into $_POST
, but you still can get the contents of your input doing this:
$jsonStr = file_get_contents("php://input");
$json = json_decode($jsonStr);