简体   繁体   English

如何在PHP中接收ajax发送的JSON数据

[英]how to Receive JSON data sent by ajax in PHP

I have the data that want sent to backend, its look like我有想要发送到后端的数据,它看起来像

function lihat(){
    let id = "12345678";
    let profile = [{name:"dave", department : "Engginering"},
                   {name:"Tedd", department : "Engginering"}]
    $.ajax({
        type:'POST',
        url:'pages/dashboard/dashboard_be.php'
        data:{
            cekload  : true,
            keys     : id,
            dataList : profile 
        },
        success:function(data){
            console.log(data);
        }
   })

the question, how can I receive all of datas sent by ajax in php script this what I've tried问题,我怎样才能在 php 脚本中接收 ajax 发送的所有数据,这是我试过的

    $id      = $_POST['keys'];
    $cekload = $_POST['cekload'];
    $data    = json_decode($_POST['dataList'];);

   //I wanna parsing the dataList object and then loop it, how to make it ?

thanks, before谢谢,之前

If you're trying to send/receive javascript objects, you need to convert the object to a string before sending and decode it back in php (into an array maybe) before reading.如果您尝试发送/接收 javascript 对象,则需要先将 object 转换为字符串,然后再将其发送并解码回 php(可能是数组),然后再读取。

<script>
    let id = "12345678";
    let profile = [{name:"dave", department : "Engginering"},
                   {name:"Tedd", department : "Engginering"}]
    $.ajax({
        type:'POST',
        url:'pages/dashboard/dashboard_be.php',
        data:{
            cekload  : true,
            keys     : id,
            dataList : JSON.stringify(profile) 
        },
        success:function(data){
            console.log(data);
        }
   });
</script>

PHP code: PHP 代码:

<?php 
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'], true);

echo $id;
echo $cekload;
print_r($data);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM