访问PHP中JQuery AJAX发送的数据

时间:2015-07-25 04:51:33

标签: php jquery ajax

我无法使用JQuery的ajax方法访问发送到php脚本的数据。

<?php
    if(isset($_POST["data_to_send"])) {
        $data_received =  $_POST["data_to_send"];
        echo $data_received;
    }
    ?>

    <!DOCTYPE html>
    <html>
        <head>
            <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
            <script>
                $(document).ready(function(){
                    function send_data(){
                       var request = $.ajax({
                          type: "POST",
                          url: "test.php",
                          data: {data_to_send:"data_object"},
                          success:function(data){
                              alert(data);
                          }
                        });
                    }
                    $('button').click(send_data);
                });
            </script>
        </head>

        <body>
            <button>Click to send data</button>
        </body>
    </html>

ajax调用成功,因为调用了成功回调。但是,在成功调用ajax后,$ _POST数组仍为空。我做了那个ajax调用后,我不确定为什么$ _POST为NULL。

1 个答案:

答案 0 :(得分:2)

<?php
if(isset($_POST["data_to_send"])) {
    $data_received =  $_POST["data_to_send"];
    echo $data_received;
    exit(); <-- add this line 
}
?>
相关问题