AJAX 发布到同一页面的请求未填充 $_POST

AJAX request posted to same page does not populate $_POST

我正在处理一个文件 form.php,它需要使用 AJAX 请求处理用户输入,这样页面就不会重新加载。用户有 2 个选项 - 检查或刷新数据。下面是代码。问题是 $_POST 没有被填充。当检查 Firefox 开发工具中的网络选项卡时,它显示请求正在发生。

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body>
        <form action="" method="post">
            <p>Select action for data -</p>
            <input type="radio" name="action" id="check" value="check">
            <label for="check">check</label>
            <br>
            <input type="radio" name="action" id="refresh" value="refresh">
            <label for="refresh">refresh</label>
            <br>
        </form>
        <script>
            $(document).ready(function() {
                $("input[type=radio][name='action']").change(function() {
                    var action = $("input[name='action']:checked").val();
                    executeAjax(action);
                });
            });

            function executeAjax(action) {
                return $.ajax({
                    method: "POST",
                    data: { action: action }
                })
                .done(function() {
                    console.log('success - ' + action + ' is the action');
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('ERROR');
                    console.log(jqXHR.status);
                    console.log(textStatus);
                    console.log(errorThrown);
                });
            }

        </script>
    </body>
</html>

<?php
echo '<hr>';
echo 'post - ' . json_encode($_POST) . '<br>';
$action = isset($_POST['action']) ? $_POST['action'] : 'no value';
echo $action;
// put logic here for what to do with with data based on value in $action'
?>

请求在“网络”选项卡中显示成功:

控制台显示来自 AJAX 调用的 .done 部分的成功消息:

那么,为什么 $_POST 不包含具有用户选择的任何值的键 'action'

在您的代码中,您没有使用 ajax 方法的响应。

           done(function(reposne) {
                console.log('success - ' + action + ' is the action');
                console.log(response);
            })

您还对 ajax 方法使用了相同的 form.php。所以你的 ajax 响应将打印表单 html,然后你的 php $_POST 相关代码。

能否将您的 php 代码放在页面顶部,如果发布了表单,请退出。否则打印表格

<?php
if(!empty($_POST)){
   // enter code here
   exit;
}
?>
<html> 
...
</html>