通过post将结构化数据传递给php

时间:2012-07-05 17:43:13

标签: php javascript post

假设我有以下数据:

var arr = [], arr1 = [], arr2 = [], arr3 = [], arr4 = [];
var a = 'something', b = 'else';
arr1['key1-1'] = 'value1-2';
arr1['key1-2'] = 'value1-2';
for (var i = 0; i < someCond; i++) {
    arr = [];
    arr['key2-1'] = 'value2-1';
    arr['key2-2'] = 'value2-2';
    arr2.push(arr);
}

现在我需要将它的漏洞传递给php脚本。

我将它打包成一个变量,如下所示:

var postVar = {
    a: a,
    b: b,
    arr1: arr1,
    arr2: arr2
};

我正在使用jQuery所以我试着像这样发布:
1)

//Works fine for a and b, not for the arrays
$.post('ajax.php', postVar, function(response){});

这个:
2)

var postVar = JSON.stringify(postVar);
$.post('ajax.php', {json: postVar}, function(response){});

使用php文件

$req = json_decode(stripslashes($_POST['json']), true);

也不起作用。

我应该如何构建/格式化数据以将其发送给PHP?

由于

修改
情况1: 的console.log(postVar); console.log(postVar)

PHP print_r($ _ POST)响应: 排列 (     [a] =&gt;某物     [b] =&gt;其他 )

如您所见,php端没有数组(对象)。

案例2:
当我添加以下内容时:


    postVar = JSON.stringify(postVar);
    console.log(postVar);

我得到了 {“a”:“something”,“b”:“else”,“arr1”:[],“arr2”:[[],[],[]]}
使用console.log(postVar)

所以这似乎是这种情况下的问题......对吧?

2 个答案:

答案 0 :(得分:0)

你应该在添加像这样的striplashes之前检查magic_quotes

if( get_magic_quotes_gpc() ) {
    $jsonString = stripslashes( $jsonString );
}
$data = json_decode( $jsonString );

我建议你应该关掉魔法引号......这根本不是魔法

答案 1 :(得分:0)

事实证明,尽管Arrays 对象,但JSON.stringify忽略了Arrays上的非Array属性。所以我必须明确地将所有变量声明为对象。除了真正用作数组的arr2之外。

这里是完整的代码:

var arr = {}, arr1 = {}, arr2 = [];
var a = 'something', b = 'else';
arr1['key1-1'] = 'value1-2';
arr1['key1-2'] = 'value1-2';
for (var i = 0; i < 3; i++) {
    arr = {};
    arr['key2-1'] = 'value2-1';
    arr['key2-2'] = 'value2-2';
    arr2.push(arr);
}

var postVar = {
    a: a,
    b: b,
    arr1: arr1,
    arr2: arr2
};


postVar = JSON.stringify(postVar);
$.post('ajax.php', {json: postVar}, function(response){});

在PHP方面:

$req = json_decode($_POST['json'], true);
print_r($req);


希望这可以帮助其他人解决同样的问题。

相关问题