jQuery的AJAX没有发布数据

时间:2016-04-09 11:55:02

标签: javascript php jquery ajax

我想使用jQuery的AJAX函数将密钥和值对发送到PHP文件,但该函数不发送数据。

PHP代码在同一个" Tester.php"文件与HTML代码一起显示如下:

<?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
(
)

但是打印的数组应该包含&#34; requestData:true&#34;从传递给$ _POST数组的数据,但这个数组是空的。我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:1)

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