将JQuery .post变量动态传递给PHP

时间:2014-11-17 15:39:37

标签: php jquery ajax

我试图在单个页面中将JQuery变量传递给PHP代码。似乎JQuery变量正在触发(我得到了确认警报),但它没有被PHP读取。我该如何解决? *为清晰起见而编辑

 <!DOCTYPE html>
    <html>
    <head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
                $(document).ready(function(){
                    $("div").click(function(){
                        var pastDATE = $(this).text();
                        $.post("testclick.php", 'pastDATE', function() {
                            alert(pastDATE, "post success");
                        });
                    });
                });
                /*
                var pastDATE = (div.calendar-head
                $.ajax({
                    type: "POST",
                    url: "testclick.php",
                    data: {pastDATE: pastDATE},
                    success: function(data){
                        alert(data);
                        }
                    });
                */      
        </script>
    <style>

    .calendar-head {
        display: block;
        line-height: 32px;
        font-weight: bold;
        text-align: center;
        background: #2F4F4F;
        color:  #2F4F4F;
        background: rgba(0, 0, 0, 0.35);
        }

    </style>    
<body>

<div class="calendar-head">This</div>

<?php

/*attempted to start a session so when page is refreshed the variable remains*/

session_start();
    $_SESSION['pastDATE'] = $pastDATE;

$pastDATE = $_POST['pastDATE'];

if(isset($_POST['pastDATE'])){
    $pastDATE = $_POST['pastDATE'];
    echo "set";
    }

echo "$pastDATE";
?>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

$.post("testclick.php", { pastDATE: pastDATE }, function() {
    alert(pastDATE, "post success");
});

应该做的伎俩

答案 1 :(得分:0)

将JavaScript代码更改为:

$(document).ready(function(){
    $("div").click(function(){
        var pastDATE = $(this).text();
        $.post("testclick.php", { data:pastDATE }, function(result) {
            alert(pastDATE, "post success");
        });
    });
});

阅读PHP,如$_REQUEST['data']