假设我有以下数据:
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:
控制台日志(postVar);
PHP print_r($_POST) 响应:
大批
(
[a] => 某物
[b] => 其他
)
如您所见,php 端没有数组(对象)。
案例二:
当我添加以下内容时:
postVar = JSON.stringify(postVar); console.log(postVar);
我明白了
{"a":"something","b":"else","arr1":[],"arr2":[[],[],[]]}
使用 console.log(postVar)
所以这似乎是这种情况下的问题……对吧?
最佳答案
你应该在添加这样的 stripslashes 之前检查 magic_quotes
if( get_magic_quotes_gpc() ) {
$jsonString = stripslashes( $jsonString );
}
$data = json_decode( $jsonString );
我建议你关掉魔术引号……这根本不是魔术
关于php - 通过post将结构化数据传递给php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11349664/