javascript - jQuery 的 AJAX 不发布数据

标签 javascript php jquery ajax

我想使用 jQuery 的 AJAX 函数将键和值对发送到 PHP 文件,但是该函数没有发送数据。

PHP 代码与 HTML 代码位于同一个“Tester.php”文件中,如下所示:

<?php
if (array_key_exists("REQUEST_METHOD", $_SERVER) && $_SERVER["REQUEST_METHOD"] == "POST") {
    echo "<pre>";
    print_r($_POST); // always empty, no clue why!
    echo "</pre>";
    exit();
}
?>

<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script>
        $(document).ready(function() {
            $.ajax({
                type: "POST",
                url: "Tester.php", // the same file/page
                data: {
                    requestData: true,
                    message: "please print me!"
                },
                success: function(data) {
                    document.write("success!");
                    document.write(data);
                },
                error: function(xmlHttp) {
                    document.write("error!");
                    document.write(xmlHttp.responseText);
                }
            });
        });
    </script>
</head>
<body>
    <p>Testing...</p>
</body>
</html>

这打印:

success!
Array
(
)

但是打印的数组应该包含传递给 $_POST 数组的数据中的“requestData: true”,但该数组却是空的。我做错了什么?谢谢!

最佳答案

HTML 文件 (36516400.html)

<html>
    <head>
        <title>36516400</title>
        <script type="text/javascript" src="../../../assets/js/script.js"></script>
    </head>

    <body>
        <h1>Welcome</h1>
        <script type="text/javascript">
            $(document).ready(function(){
                $.ajax({
                    type:'POST',
                    data:{
                        'requestData':true,
                        'message':"please print me!"
                    },
                    url:'responce.php',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    success:function(data){
                        alert(data);
                    }
                });
            })
        </script>
    </body>
</html>

PHP 文件 (responce.php)

<?php
    echo "<pre>";
    print_r($_REQUEST);
    echo "<pre>";
?>

Chrome 控制台中的请求

enter image description here

关于javascript - jQuery 的 AJAX 不发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516400/

相关文章:

javascript - 将 onclick 添加到来自 javascript 的标签

php - Mysql - 从多个表中选择而不产生重复数据

javascript - 使用 jQuery 事件

javascript - CSS/cut an img's width when reducing the screen/window width 减少屏幕/窗口宽度

javascript - 如何清除 Vue v-list 中的事件项目?

php - TCPDF 绘制带边框和填充的圆

javascript - 在 jQuery 中重复单击事件而不删除先前的单击效果

javascript - 在特定字符处强制换行

javascript - jQuery 中的事件绑定(bind)

javascript - 多个动态下拉选择菜单不起作用 - PHP MySQL Jquery