为什么当我获取数据时,数据似乎未定义/为空?我使用jquery.post()将数据从js发送到php

apeeds0o  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(423)

我的问题是:我正在使用jquery的 $.post 方法。出于某种原因, data 似乎没有定义。
让我解释一下我的代码是如何构造的。。。
1.我有以下带有onclick功能的按钮:

$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 id='deleteID_$data->id' onclick='Delete($data->id, $tableName, $idName)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";

相同的代码缩进以提高可读性:

$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 
                id='deleteID_$data->id' 
                onclick='Delete($data->id, $tableName, $idName)' 
                class='btn btn-danger btn-sm btnBorrar'
            >
                <i class='material-icons' value='delete'>delete</i>
            </button>
        </div>
    </div>
";

2.我的 Delete() 功能:

function Delete(id, tableName, idName) {
    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {

        console.log("First parameter: " + id + "\nSecond parameter: " + tableName + "\nThird parameter: " + idName); // I GET MY FUNCTION PARAMETERS.
        console.log("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id); // I GENERATE MY POST URL CORRECTLY.

        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(data) {
            console.log("My data: " + data);
            if(data == 1) {
                console.log("Data OK");
                //$().hide();
            }
            else if (data == '') {
                console.log("Data empty");
            }
            else if (data == null) {
                console.log("Data null");
            }
            else if (data) {
                console.log("Data exist");
            }
            else {
                console.log("Other reasons");
            }
        });
    }
}

3.这样你就可以看到 console.log() 返回:

为什么 data 没有定义?
编辑:这是我的完整代码:(我不想上传完整代码以免造成混乱,我试图最小化并压缩它)。

<?php

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

    $test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);

    $action = $_POST['action'];
    if(empty($action)){
        $GET = get_vars_for_get();
        $action = $GET['action'];
    }

    switch($action){

        case 'datosTabla': // OK.

            //print_r($_POST['action']);
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);

            break;

        case 'deleteRegistro':
            //die("Hola");
            $tableName = $_POST['tableName']; // Nombre de la tabla de la base de datos (String).
            $id = $_POST['id'];               // ID (int).
            $idName = $_POST['idName'];       // Nombre del campo ID (String).

            echo $tableName;

            //echo deleteRegistro($tableName, $id, $idName);

            break;

        case 'showtable': // OK.

            $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
            $tableName = $_POST['tableName'];
            $tableName = json_encode($tableName);

            //$field = json_decode($_POST['tableFields'],1)[0];
            //$field = json_encode($field);

            $idName = $_POST['id'];
            $idName = json_encode($idName);

            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 id='deleteID_$data->id' onclick='Delete($data->id, $tableName, $idName)' 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, idName){
                    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {

                        console.log("First parameter: " + id + "\nSecond parameter: " + tableName + "\nThird parameter: " + idName); // I GET MY DATA CORRECTLY.
                        console.log("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id); // I GET MY DATA CORRECTLY.

                        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(data){

                            console.log("Typeof: " + typeof(data));
                            console.log("My data: " + data);
                            console.log("My data: ", data);
                            console.log("[" + data + "]")

                            if(data == 1){
                                console.log("Data OK");
                                //$().hide();
                            }
                            else if (data == ''){
                                console.log("Data empty");
                            }
                            else if (data == null) {
                                console.log("Data null");
                            }
                            else if (data) {
                                console.log("Data exist");
                            }
                            else {
                                console.log("Other reasons");
                            }
                        });
                    }
                }

                $(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;
}
?>
dfty9e19

dfty9e191#

如果您想要恢复数据,请使用 $.get ```
$.get("/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(result){
console.log(result);
});

kiayqfof

kiayqfof2#

您在函数delete()中提供的url完全错误,

<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id

此url适用于get方法not post,用于发布任何不需要将数据放入url的内容。

$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", { 
            action: "deleteRegistro",
            id: id,
            tableName: tableName,
            field: field
        }, function (data, status){
                if (status === 'error') {
                    console.log("Not deleted");
                }
                else if (status === 'success') {
                    console.log("Deleted successfully");                                
                }
                if(data != '') console.log("The response is" + data);
                else console.log("There is not response");
            });

这是 function(data, status) 用于在何处处理错误 data 是来自url和 status 是发送到url的数据的状态。
你必须小心给出条件 if(data == 1) 哪里 data 是来自url的响应,因此它不是布尔值。
在数据发布的另一方面处理请求是非常重要的,所以请检查一次。
有关 $.post() 参观这里

相关问题