繁体   English   中英

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

[英]passing structured data to php via 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] =>某事[b] => else)

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

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

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

我明白了
{ “一个”: “东西”, “B”: “其他”, “ARR1”:[], “ARR2”:[[],[],[]]}
使用console.log(postVar)

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

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

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

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

事实证明,尽管Arrays Objects,但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);


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM