jquery -通过POST (ajax)发送JSON数据并在php中检索


jquery - Send JSON data via POST (ajax) and retrieve in php

目前我正试图使用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是元素的array,所以试试这个:

foreach ($result as $data) { 
    echo $data['name']." : ".$data['gender']; //etc.   
}

试试这个:

   $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {'students': studentString}
    })

process.php

foreach ($result as $k => $value) { 
    $msg = "name is:" . $value['name']; 
    $msg .=  ", gender is:" . $value['gender'];
    // add other 
    echo $msg."<br>";
}