PHP从javascript数据对象

时间:2015-06-10 13:21:56

标签: php jquery

我在jquery中创建了一个数据对象,并使用post方法将其传递给php

var PD = { currentPage : 1, rowCount : 10, search : 5 };

post method --> data = PD

在php页面中如果我获得超级全球$ _POST我有这个

var_dump($_POST) --> Array ( [data] => [object Object] )

在php中如何阅读$ _POST ['数据']值? 谢谢

编辑(完整代码)

var PD = { currentPage : 1, rowCount : 10, search : 5 };    
    PD = JSON.stringify(PD);

redirectPost('index.php', { data : PD });

var redirectPost = function(location, args) {
    var form = '';
    $.each(args, function(key, value) {
        form += '<input type="hidden" name="'+key+'" value="'+value+'">';
    });
    $('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
};

PHP

$data = json_decode($_POST['data']);
var_dump($data); <-- NULL

3 个答案:

答案 0 :(得分:0)

看起来你正在寻找json_decode() - 函数。但是,这不会创建PHP对象,但会变成这样的数组:$data['currentPage']。看看你是否获得了更多运气:

$data = json_decode($_POST['data']);
var_dump($data);

答案 1 :(得分:0)

看起来您的JavaScript对象已转换为字符串[object Object],您需要在发布之前JSON.stringify JavaScript对象。

var PD = { currentPage : 1, rowCount : 10, search : 5 };
// ensure our data is serialised in a format we can read later with PHP.
PD = JSON.stringify(PD);

post method --> data = PD

收到你的$ _POST数据后,菲尔指出你应该能够json_decode

答案 2 :(得分:0)

首先,你的javascript永远不会工作。有一些javascript问题,比如在声明之前调用变量,值中的双引号会干扰json。字符串化

value="{"currentPage":1,"rowCount":10,"search":5}"

看起来并不好看(( 如果你像我在这里一样解决它 https://jsfiddle.net/79dLek7p/

var PD = { currentPage : 1, rowCount : 10, search : 5 };    
    PD = JSON.stringify(PD);

var redirectPost = function(location, args) {
    var form = '';
    $.each(args, function(key, value) {
        form += '<input type="hidden" name="'+key+'" value=\''+value+'\'>';
    });
    $('<form action="'+location+'"  method="POST">'+form+'</form>').appendTo('body').submit();
};

redirectPost('index.php', { data : PD });

您将看到$ _POST [&#39;数据&#39;]作为json编码的字符串,您可以按照之前的建议使用json_decode。

相关问题