目前我正在尝试使用ajax通过POST发送对象以在接收端进行处理。
var studentString = JSON.stringify(studentArray);
console.log(studentString);
// process the form
$.ajax({
type: 'POST',
url: 'process.php',
data: {'students': studentString},
dataType: 'json',
encode: true
})
JSON.stringify 后的输出如下,所以到目前为止一切似乎都很好。
[{"name":"bob","gender":"m","level":"4","topic":"subtraction"},
{"name":"john","gender":"f","level":"3","topic":"addition"}]
在接收端(php 端),我尝试使用 json_decode 检索数据,如下所示:
$result = json_decode($_POST['students'], true);
然而,在那之后我就不知所措了。如何循环遍历结果数组以一次输出每个学生的详细信息?或者输出(例如)每个学生的名字?我尝试过各种变体
foreach ($result as $k => $value) {
$msg .= $k . " : " . $result[$k];
}
...但我没有任何运气。任何帮助,将不胜感激。
最佳答案
$result
是一个数组
元素,所以试试这个:
foreach ($result as $data) {
echo $data['name']." : ".$data['gender']; //etc.
}
关于javascript - jquery - 通过 POST (ajax) 发送 JSON 数据并在 php 中检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334058/