繁体   English   中英

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

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

想象一下,我有一个带有删除寄存器按钮的 CRUD 表。

在此处输入图片说明

我想做什么?

  • 基本上,我想要的是,函数Delete() (3 个变量),它们通过 POST 方法再次到达我的 PHP,这样我就可以使用这些数据进行查询并删除注册表数据库。

我想传递的信息如下:

$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 请求,向我的 PHP 发送一个action

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() );
      
}

暂无
暂无

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

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