在PHP中处理通过jquery发送的json数组

时间:2013-11-18 10:15:14

标签: php jquery json

我正在尝试使用通过JQuery发送的PHP中的JSON数组。发送到服务器的数据采用以下格式:

[{"id":"7","start":"00:00","end":"02:30","date":"2013-11-15"},{"id":"10","start":"23:00","end":"23:30","date":"2013-11-15"},{"id":"5","start":"13:00","end":"14:00","date":"2013-11-16"},{"id":"6","start":"18:00","end":"18:45","date":"2013-11-16"}]

我通过此功能将上述数据发送到服务器:

$('#updateOverallChanges').click(function(event){
            var formArray = new Array();
            $('.updateForm').each(function( index ) {
                formArray.push($(this).JSONFromSerialize());
            });


            $.ajax({
                url: 'inner/formTester.php',
                data: JSON.stringify(formArray),
                type: 'POST',
                contentType: "application/json; charset=utf-8",
            });
        });

函数JSONFromSerialize负责转换有意义的json数据中的表单:

(function($) {
    $.fn.JSONFromSerialize = function() {

        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [ o[this.name] ];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

我使用以下PHP代码来处理JSON数组:

<?php
$params = json_decode($_POST[]);
echo $params;
?>

但上面的代码给出了以下输出:

Fatal error: Cannot use [] for reading in C:\xampp\htdocs\holidaymanager\inner\formTester.php on line 2

第二次尝试

将有效负载修改为名称值对:

 var postData = {
                data : formArray
            };

            $.ajax({
                url: 'inner/formTester.php',
                data: JSON.stringify(postData),
                type: 'POST',
                contentType: "application/json; charset=utf-8",
            });

帖子数据是:

{"data":[{"id":"7","start":"00:00","end":"02:30","date":"2013-11-15"},{"id":"10","start":"23:00","end":"23:30","date":"2013-11-15"},{"id":"5","start":"13:00","end":"14:00","date":"2013-11-16"},{"id":"6","start":"18:00","end":"18:45","date":"2013-11-16"}]}

php代码仍然失败:

<?php
$params = json_decode($_POST["data"]);
echo $params;

?>

错误:

Notice: Undefined index: data in C:\xampp\htdocs\holidaymanager\inner\formTester.php on line 2

请建议我如何使用发送到用PHP编写的后端的JSON数组。

1 个答案:

答案 0 :(得分:2)

   $.ajax({
            data : {data:JSON.stringify(postData)},
   })
php中的

  $params = $_POST['data']; // add this line 
  $params = json_decode($params,true); 
  print_r($params);

  $params = json_decode($_POST,true);
  print_r($params);

你已经使用json_Decode()...

传递第二个参数 true

希望它可以帮到你