简体   繁体   English

使用带有jQuery的POST请求将数据发送到服务器

[英]Send data to the server using POST request with jQuery

What I want to do:我想做的事:

  • I'm trying to send data to my server using $.post jQuery shortcut.我正在尝试使用$.post jQuery 快捷方式将数据发送到我的服务器。

What is the problem:问题是什么:

  • My program doesn't enter in my switch case , maybe because my action it isn't sending properly.我的程序没有进入我的switch case ,可能是因为我的action没有正确发送。

What I'm trying to do:我正在尝试做的事情:

  • I created a table and one of my elements is a button with an onclick JavaScript function: <button onclick='Delete()'></button> .我创建了一个表格,其中一个元素是一个带有onclick JavaScript 函数的<button onclick='Delete()'></button><button onclick='Delete()'></button>

  • My JavaScript function:我的 JavaScript 函数:

function Delete(){
    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro", function(data){
        if(data){
            console.log("Deleteeeed");  
        }
        else {
            console.log("Not deleted :(");
       }
    });
}
  • My switch case statement:我的switch case语句:
switch($_POST['action']){
    case 'deleteRegistro': // NOT OK
        ?>
            <script>
                alert("I'm in deleteRegistro");
            </script>
        <?php 
        
        break;
}
  • What happen when I click on the button:当我点击按钮时会发生什么:

在此处输入图片说明

This, should work because I'm passing my action deleteRegistro in my post request to my server (php).这应该可以工作,因为我将我的 post 请求中的操作deleteRegistro传递到我的服务器 (php)。

I need some help, what I'm doing wrong?我需要一些帮助,我做错了什么?

This is my full code if you want to check it out:如果您想查看它,这是我的完整代码:


<?php

include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');

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

    switch($_POST['action']){
        
        case 'datosTabla': // OK.
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            
            break;
        
        case 'deleteRegistro': // NOT OK
            ?>
            <script>
                alert("I'm in deleteRegistro");
            </script>
            <?php 
            break;
            
        case 'showtable': // OK.
            
            $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
            $tableName = $_POST['tableName'];
            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()' 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);
            
            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(){
                    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro", function(data){
                        if(data){
                            console.log("Deleteeeed");  
                        }
                        else {
                            console.log("Not deleted :(");
                        }
                    });
                }
                
                $(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;      
}
?>

You are passing the action in the query string, not the request body, so it will be available in $_GET and not $_POST .您正在查询字符串中传递操作,而不是请求正文,因此它将在$_GET而不是$_POST可用。

The PHP superglobals $_GET and $_POST do not refer (directly) to the request type. PHP 超全局变量$_GET$_POST不(直接)引用请求类型。 They refer to where an HTML form will put data from an input depending on the method attribute.它们指的是 HTML 表单将根据method属性放置来自输入的数据的位置。

Any kind of HTTP request can include a query string in the URL and this will be put in the $_GET superglobal.任何类型的 HTTP 请求都可以在 URL 中包含一个查询字符串,这将被放入$_GET超全局变量中。

Not all HTTP requests can have a request body, but many (including POST and PUT) can.并非所有 HTTP 请求都可以有请求正文,但很多(包括 POST 和 PUT)可以。 PHP will populate $_POST with data in the request body if it is encoded in a format PHP understands and the Content-Type is correct.如果以 PHP 理解的格式编码并且Content-Type正确,PHP 将使用请求正文中的数据填充$_POST (PHP might also check the request type and only do this for POST requests, it isn't something I've investigated). (PHP 也可能会检查请求类型,并且只对 POST 请求执行此操作,这不是我调查过的)。

You are posting to the file in a wrong way that might be the issue as far as I could understand it.您以错误的方式发布到文件中,据我所知,这可能是问题所在。

$.post("URL", {
            action: "deleteRegistro"
        }, function (data, status) {
        //  alert (data + '\n' + "status" + status);
            if (status === 'error') {
                console.log("Not deleted"); // For debugging purpose
            } else if (status === 'success') {
              console.log("Deleted successfully");
            }
        });

Put the correct URl in place of "URL" No need to change anything in switch case tho.将正确的 URl 替换为“URL” 无需在 switch case 中更改任何内容。

But even after this you may not see your data in table got deleted, you need to refresh the page.但即使在此之后您可能看不到表中的数据被删除,您需要刷新页面。

As you have all these functionalities in single page I suggest you to use hidden form to post the data.由于您在单页中拥有所有这些功能,我建议您使用隐藏表单来发布数据。

Maybe this php code doesnt work in js.也许这个 php 代码在 js 中不起作用。 You can get it in a hidden input like that ;您可以在这样的隐藏输入中获取它;

<input id="takeUrl" type="hidden" value="<?=SITE_URL_ADMIN?>">
let url = $('#takeUrl').val();

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

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