从$_POST中读取json中的关联数组


Read associative array from json in $_POST

我使用jQuery发布json对象到我的php应用程序。

jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });

从firebug中提取的json字符串看起来像这样

{ "data" : [ { "contents" : "This is some content",
        "selector" : "DIV.subhead"
      },
      { "contents" : "some other content",
        "selector" : "LI:nth-child(1) A"
      }
    ],
  "page" : "about_us.php"
}

在php中,我试图把它变成一个关联数组。

目前为止我的php代码是

<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>

ajax调用的响应应该是"about_us.php",但是返回的是空白

如果请求体不是标准的urlencoded形式,

$_POST将不会被填充。

相反,像这样从只读的php://input流中读取以获得原始请求体:

$value = json_decode(file_get_contents('php://input'));

可以避免使用JSON.stringifyjson_decode:

jQuery.post("save.php", dataToSend, function(data){ alert(data); });

:

<?php
echo $_POST['page'];
?>

更新:

…但是如果你真的想使用它们,那么:

jQuery.post("save.php",  {json: JSON.stringify(dataToSend)}, function(data){ alert(data); });

:

<?php
$value = json_decode($_POST['json']);
echo $value->page;
?>

如果您想要关联数组,则将第二个参数传递为true,否则它将继续返回对象。

$value = json_decode(stripslashes($_POST),true);

尝试:

echo $value->page;

因为json_decode的默认行为是返回stdClass类型的对象。

或者,将第二个可选的$assoc参数设置为true:

$value = json_decode(stripslashes($_POST), true);
echo $value['page'];

看起来jQuery可能会以urlencoded形式编码javascript对象,然后填充到$_POST中。至少从他们的例子中可以看出。我会尝试在你的对象传递到post()没有字符串化它。

如果您想使用json数据作为关联数组,您可以尝试如下:

<?php 
$json = 'json_data'; // json data
$obj = jsondecode($json, true); // decode json as associative array 
// now you can use different values as 
echo $obj['json_string']; // will print page value as 'about_us.php' 

for example: 
$json = { "data" : [ { "contents" : "This is some content",
    "selector" : "DIV.subhead"
   },
   { "contents" : "some other content",
    "selector" : "LI:nth-child(1) A"
   }
  ],
"page" : "about_us.php"
}
$obj = json_decode($json, true); 
/* now to print contents from data */
echo $obj['data']['contents']; 
 // thats all 
?>