jquery发布ajax调用会话不起作用

I'm really lost here while trying to send a session with my jquery ajax post call, here is a simplified example of my code.

File fom which request is sent:

<?php
    session_start();
    $token = md5(rand(1000,9999));
    $_SESSION['contactToken'] = $token; 
?>

<script type="text/javascript">
    $.post(ContactUrl,{req:"contact_sub",tok:"<?php echo $token; ?>"},function(contactAns){
        alert(contactAns); return false;
    });
</script>

File request is sent to:

<?php
if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="url"){
    if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) ){

        session_start();
        $token = $_POST['tok'];
        $sess_token = $_SESSION['contactToken'];

        if($token == $sess_token){
            echo "sessions match"; exit();
        }
        else{
            echo "sessions does not match"; exit();
        }
    }
    else{echo "error"; exit();}
}
else{echo "error"; exit();}
?>

At first the session was not getting recognized, I made all the checks - made sure it was setup in the first place made sure it was posted, declared session start on both pages, never the less if i tried to do this on the second file:

<?php
session_start();
$token = $_POST['tok'];
$sess_token = $_SESSION['contactToken'];

print_r($_SESSION['contactToken']); exit();
?>

I would get an empty alert. Then I transferred the session start to the top of my script on the second page and started getting a value for the session:

<?php
session_start();
$sess_token = $_SESSION['contactToken'];

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="url"){
    if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) ){

        $token = $_POST['tok'];
        echo "$token, $sess_token"; exit();

    }
    else{echo "error"; exit();}
}
else{echo "error"; exit();}
?>

And what I'm getting now is that the posted variable changes each time I refresh the page but the $sess_token always gives me the same value: 0589dd536fd043ff3865f8223fef3030

I really dont understand this wierd behavior, can some one please assist me with this?

查看全部
dtz88967
dtz88967
2015/09/08 00:45
  • session
  • php
  • ajax
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复