首页 > 解决方案 > 如何强制服务器使用 POST 而不是 GET

问题描述

像这里的很多人一样,我遇到了问题。我正在尝试使用 html 按钮(不在表单中(我应该吗?))删除 sql 库中的某些内容。为了实现这一点,我使用了 Ajax 和 PHP。我的 Ajax 代码成功,一切正常。但是 PHP 正在寻找一个 GET 请求,所以 POST 保持为空。

这是我的阿贾克斯:

    function deleteImg(arg){
      console.log("I'm now in the function");
      var url = window.location.href;
      $.ajax({
           type: "POST",
           url:url,
           data:{action:'delete', id:'arg'},
           beforeSend: function(xhr){xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")},
           success:function(html) {
                console.log("Success :) ");
           }

      });
}

这是我的php:

<?php
    
    session_start();
    
    $dir    = '../uploads/';
    $files1 = scandir($dir);
    
    function remove($id){
        $file = $dir . $files1[$id];
        unlink($file);
    }
    
    
    if ($_SERVER['REQUEST_METHOD'] == 'GET') {
     echo "<script>alert( \" request method is get \" )</script>";
     }
    
    
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      echo "<script>alert( \" La request method is post \" )</script>";
      }
    
    if(isset($_POST['action'])){
    
      if( $_POST['action'] == 'delete'){
            header('Location: projets.php');
            remove($id);
      }
    
    }
?>

这是我的第一个问题,英语不是我的主要语言,所以如果有什么遗漏,我很抱歉。

标签: phpajaxpostget

解决方案


您的remove函数尝试使用全局上下文中的变量,但在函数本身中是未知的。要允许在函数中访问这些变量,可以将它们作为参数添加到函数中,或者在函数global内声明。

<?php
<?php
    error_reporting( E_ALL );
    session_start();
    $message=false;

    $dir    = '../uploads/';
    $dir=__DIR__ . '/upload';   #for MY environment
    $files = scandir( $dir );


    function remove( $id ){
        global $dir;
        global $files;
        if( array_key_exists( $id, $files ) ){
            $file = realpath( $dir . '/' . $files[ $id ] );
            return unlink( $file );
        }
        return false;
    }




    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $args=array(
            'action'    =>  FILTER_SANITIZE_STRING,
            'id'        =>  FILTER_SANITIZE_STRING
        );
        $_POST=filter_input_array( INPUT_POST, $args );
        extract( $_POST );


        if( !empty( $action ) && !empty( $id ) ){
            $status=remove( $id );
            $message=$status ? 'File deleted' : 'Error: Unable to find file';
        }

        exit( $message );
    }
?>



<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Delete...</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <script>
            function deleteImg( event, arg ){
                var url = window.location.href;
                $.ajax({
                    type:"POST",
                    url:url,
                    data:{
                        action:'delete',
                        id:arg
                    },
                    success:function( r ) {
                        console.log( r );
                        event.target.parentNode.removeChild( event.target );
                    }
                });
            }
        </script>
    </head>
    <body>
        <?php
            foreach( $files as $index => $file ){
                if( $file!='.' && $file!='..' && !is_dir( $file ) ) {
                    printf('<a href="#" onclick="deleteImg( event, \'%d\' )">Delete %s</a><br /><br />', $index, $file );
                }
            }
        ?>
    </body>
</html>

推荐阅读