如何使用 onclick 函数和 AJAX 将数据从 PHP 传递到 JS 并再次传递到 PHP

How to pass data from PHP to JS and to PHP again using an onclick function and AJAX

假设我有一个 CRUD table,带有一个删除寄存器的按钮。

我想做什么?

我要传递的信息如下:

$data->id // Value example: 1
$tableName // Value example: users_test
$field // Value example: id

我的按钮:

<button onclick='Delete($data->id, $tableName, $field)'>Delete</button>

我的 Delete JS 函数(基本上我创建了一个 POST 请求发送一个 action 到我的 PHP.

function Delete(id, tableName, field){
    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
        action: "deleteRegistro"
        }, function (data, status) {

        if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
            if (status === 'error') {
                console.log("Not deleted"); // For debugging purpose
            } else if (status === 'success') {
                console.log("Deleted successfully");                                
            }
        }
        else {
            return false;
        }
    });
}

我的PHP:

switch($_POST['action']){
           
    case 'deleteRegistro':
        
        $id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
        $tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
        $field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();

        break;
}

如果您需要的话,这是我的完整代码:

<?php

use GuzzleHttp\json_decode;
include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');

    $test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
    
    if ($_GET['action']){
        print_a($_GET['action']);
    }

    switch($_POST['action']){
        
        case 'datosTabla': // OK.
            
            //print_r($_POST['action']);
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            
            break;
        
        case 'deleteRegistro':
            
            $id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
            $tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
            $field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
            
            break;
            
        case 'showtable': // OK.

            $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
            $tableName = $_POST['tableName'];
            
            $field = json_decode($_POST['tableFields'],1)[0];
            //print_r($tableName);
            //print_r('<br>');
            //print_r($campo);
            
            foreach ($res as $data){                
                $data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $campo)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>"; 
                $resultados['data'][] = $data;
            }           
            
            $resultados = json_encode($resultados); // 7 PROPIEDADES
            
            foreach(json_decode($_POST['tableFields']) as $columnsDB){
                $fields[] = array('data'=>$columnsDB);
            }

            $fields[]['data'] = 'acción';
            $fields = json_encode($fields);
            
?>
            <head>
                <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
            </head>
            
            <div class="container caja">
                <div class="row">
                    <div class="col-lg-12 col-sm-12">
                        <div>
                            <table id="tablaUsuarios" class="table table-striped table-bordered table-condensed hover" style="width:100%" >
                                <thead class="text-center">
                                    <tr>
                                        <?php
                                            foreach (json_decode($_POST['tableFields']) as $columnsTH){
                                                 echo '<th>' . strtoupper($columnsTH) . '</th>';
                                            }
                                            echo '<th>ACCIÓN</th>';
                                        ?>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <script>

                function Delete(id,tableName, campo){
                    //$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro&tabla=" + tabla + "&nombre_campo=" + campo + "&id=" + id, function(data){
                    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
                        action: "deleteRegistro"
                        }, function (data, status) {
    
                        if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
                            if (status === 'error') {
                                console.log("Not deleted"); // For debugging purpose
                            } else if (status === 'success') {
                                console.log("Deleted successfully");                                
                            }
                        }
                        else {
                            return false;
                        }
                    });
                }
                
                $(document).ready(function() {
                    var datos= <?=$resultados?>;
                    var dynamicColumns = <?=$fields?>;
                    datos = JSON.stringify(datos);
                    
                    $('#tablaUsuarios').DataTable({
                        "language": {"url": "https://cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"},
                        "paging": true,
                        "lengthChange": true,
                        "searching": true,
                        "info": true,
                        "autoWidth": true,
                        "scrollX": true,

                        "ajax":{
                            "url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',
                            "method": 'POST',
                            "data":{action: "datosTabla", datos: datos}
                        },

                        "columns": dynamicColumns
                    });
                })
            </script>
<?php
        break;      
}
?>

也许你应该尝试这样的事情:

function Delete(id, tableName, field){
    $.post(
        "<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", 
        {
           action: "deleteRegistro"
           id: id, 
           tableName: tableName, 
           field: field
        }, 
        function (success) {....}
   )};

你忘记id、tableName和field了吗?

还有更新的fetch.then

function ajaxpost (divid,var1,var2,var3) {

    var pcache = (Math.floor(Math.random() * 100000000) + 1); // this is important to avoid browser cache
    var postix = [];
    
    postix["divid"] = encodeURIComponent(divid);
    postix["var1"] = encodeURIComponent(var1);
    postix["var2"] = encodeURIComponent(var2);
    postix["var3"] = encodeURIComponent(var3);
    postix["cookies"] = decodeURIComponent(document.cookie); // if you need to send cookies
    postix["windowwidth"] = encodeURIComponent($(window).width());  // optional but cool if you need to retrive more that just text....
    postix["windowheight"] = encodeURIComponent($(window).height()); 
    
    // this code will retrieve ALL localStorage and sessionStorage to send to php if you need
    for (var i = 0; i < localStorage.length; i++){ postix[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); }
    for (var i = 0; i < sessionStorage.length; i++){ postix[sessionStorage.key(i)] = sessionStorage.getItem(sessionStorage.key(i)); }
        
    fetch("/path_to_php.php?pcache="+pcache, {
      method: "POST",
      body: JSON.stringify(Object.assign({}, postix)),
      headers: {"Content-type": "application/json; charset=UTF-8"}
    }).then(function (response) { return response.text(); })
      .then(function (html) { $("#"+divid).html(html);  })
      .catch( err => console.log() );
      
}