我创建了一个对象的jQuery数组:
my_family = [
person {
name = “nick”,
age = 41,
role = “dad”
},
person {
name = “john”,
age = 4,
role = “son”
},
person {
name = “sarah”,
age = 31,
role = “mom”
},
]
我正试图通过post将其作为php数组发布到同一页面,我已经成功地做到了:
$.post("http://www.samepage.com", {my_family: my_family});
然后我想使用这些数据,但当我试图将其添加到变量或以任何方式操作它时,页面都没有响应。当我使用以下代码时,我可以在我的firebug中看到它打印到html中,但我不能将它添加到变量或任何东西中,为什么?这就是我在html:中看到的
print_r ($_POST['my_family']);
此外,它不会打印到名为"my_family"的页面,而只是"Array"。我的主要目标是循环遍历数组,并将每个"年龄"值存储到一个新数组中。通过post方法我能做什么吗?
如果您正在张贴一些更复杂的数据,您可以尝试JSON.stringify
该数据,发送它,然后用PHP解码它。
在JavaScript中:
$.post("http://www.samepage.com", {my_family: JSON.stringify(my_family)});
在PHP中:
$my_family = json_decode($_POST['my_family'], true);
print_r($my_family);
// And if you're storing 'age' values into a new array
$age_values = array();
foreach($my_family as $person) {
array_push($age_values, $person['age']);
}
在这里,您似乎正在尝试将数据读取为POST,而POST不是发布的表单,$_POST只是数据的包装器,用于
-
application/x-www-form-urlencoded(简单的内容类型形式员额)或
-
多部分/表单数据编码(用于文件上传)
在这里,基本上您可能希望读取JSON作为php的原始输入。//在php文件中。。
$data = json_decode(file_get_contents('php://input'));
print_r ( $data);