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

时间:2021-01-07 18:14:01

At the moment I'm trying to use ajax to send objects via POST to be processed on the receiving end.

目前,我正在尝试使用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
        })

The output after JSON.stringify is as follows, so everything would seem to be okay so far.

JSON后输出。stringify是这样的,所以到目前为止一切看起来都还好。

[{"name":"bob","gender":"m","level":"4","topic":"subtraction"},
 {"name":"john","gender":"f","level":"3","topic":"addition"}]

On the receiving end (php side) I'm trying to retrieve the data using json_decode, as follows:

在接收端(php端),我尝试使用json_decode获取数据,如下所示:

$result = json_decode($_POST['students'], true);

However, after that I am at a loss. How can I loop through the resulting array to output the details on each student, one at a time? Or output (for example), the name of each student?? I've tried variations of

然而,在那之后我就不知所措了。如何循环遍历结果数组以输出每个学生的详细信息,一次一个?还是输出(例如),每个学生的名字?我试着变化

foreach ($result as $k => $value) { 
    $msg .= $k . " : " . $result[$k];    
}

...but I'm not having any luck. Any help would be appreciated.

…但我运气不好。如有任何帮助,我们将不胜感激。

2 个解决方案

#1


2  

The $result is an array of elements, so try this:

$result是一个元素数组,请尝试以下操作:

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

#2


0  

Try this:

试试这个:

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

process.php

process.php

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

    echo $msg."<br>";
}

#1


2  

The $result is an array of elements, so try this:

$result是一个元素数组,请尝试以下操作:

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

#2


0  

Try this:

试试这个:

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

process.php

process.php

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

    echo $msg."<br>";
}