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

Dan*_*iel 18 php post json associative-array http-post

我正在使用jQuery将json对象发布到我的php应用程序.

jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });
Run Code Online (Sandbox Code Playgroud)

从萤火虫中拉出的json字符串看起来像这样

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

在PHP中我试图将其转换为关联数组.

到目前为止,我的PHP代码是

<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>
Run Code Online (Sandbox Code Playgroud)

对ajax调用的响应应为"about_us.php",但它返回空白.

Eve*_*ert 87

$_POST 如果请求正文不是标准的urlencoded格式,则不会填充.

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

$value = json_decode(file_get_contents('php://input'));
Run Code Online (Sandbox Code Playgroud)

  • 是的,因为application/json不是填充$ _POST的内容类型之一.只有application/form-data和application/x-www-form-urlencoded才能解析它.file_get_contents实际上是最好的方法,OP最终使用的解决方案并不优雅. (8认同)

Fra*_*ani 16

你可以避免使用JSON.stringifyjson_decode:

jQuery.post("save.php", dataToSend, function(data){ alert(data); });
Run Code Online (Sandbox Code Playgroud)

和:

<?php
echo $_POST['page'];
?>
Run Code Online (Sandbox Code Playgroud)

更新:

...但如果你真的想要使用它们,那么:

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

和:

<?php
$value = json_decode($_POST['json']);
echo $value->page;
?>
Run Code Online (Sandbox Code Playgroud)