如何获取在php中使用jquery $ _post发送的序列化数据

时间:2014-11-05 10:14:13

标签: php jquery json

我只想知道如何在php中检索这些数据? (它被序列化并以JSON格式)

这是我目前的代码:

相关的html位:

<form id="add-review-form" action="/review/save" method="post">
       <div>
            <textarea name="reviewDescription" class="review"></textarea>
            <input type="hidden" name="organisationId" value="<?=$this->organisation->id?>"/>
            <input type="hidden" name="score"/>
            <button id="save-review-button" type="button" class="small">Opslaan</button>

        </div>

</form>

Jquery位:

            // Get form as jQuery object
            var addReviewForm = $('#add-review-form');

            // Remove errors
            removeFormMessages( addReviewForm );

            // Get data
            var data = addReviewForm.serialize();
            $.post("/review/save", data, function (data, status) {
                    console.log(data);
                }
           ,"json" );

2 个答案:

答案 0 :(得分:0)

我会以这种方式调用JQuery:

$.post("/review/save", {json: JSON.stringify(data)}, 
      function (data, status) {
         console.log(data);
      }, "json" );

稍后在PHP端,您可以在解析后访问提交的json对象:

<?php
   $json_array = json_decode($_POST['json']);
?>

答案 1 :(得分:0)

您可以获取原始数据,例如

$rawdata = file_get_contents('php://input');

要从中获取json数据,您可以使用

$jsondata = json_decode($rawdata,true);

如果第二个参数为true,json_decode将返回associative数组中的结果