PHP 会话不适用于 JQuery Ajax?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1564418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:06:02  来源:igfitidea点击:

PHP session not working with JQuery Ajax?

phpjqueryajaxgomoku

提问by Bolt_Head

Update, Solved:After all this I found out that I was calling an old version of my code in the update ajax. 'boardControl.php' instead of 'boardUpdate.php' These are the kinds of mistakes that make programing fun.

更新,解决:毕竟我发现我在更新ajax中调用了我的代码的旧版本。'boardControl.php' 而不是 'boardUpdate.php' 这些是使编程变得有趣的错误类型。



我正在写一个浏览器 gomoku五子棋游戏。我有允许播放器播放的 ajax 语句。

$(document).ready(function() {
    $("td").live('click',function(){
        var value = $(this).attr('id');
        $.get('includes/boardControl.php',{play: value, bid: bid});
    });
});

value = board square location
bid = board ID

价值 = 棋盘广场位置
出价 = 棋盘 ID

Before creating a user login for player identification, the server side php had a temporary solution. It would rotate the piece state for the squares when clicked instead of knowing what player to create them for.

在创建玩家识别的用户登录之前,服务器端php有一个临时解决方案。它会在点击时旋转方块的棋子状态,而不是知道为哪个玩家创建它们。

After creating login stuff I set a session variable for the player's ID. I was hoping to read the session ID from the php during the ajax request and figure out what player they are from there.

创建登录内容后,我为玩家的 ID 设置了一个会话变量。我希望在 ajax 请求期间从 php 读取会话 ID,并找出他们来自那里的玩家。

session_start();

...

...

    $playerId = $_SESSION['char'];
    $Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
    $Result=mysql_query($Query);
    $p1 = mysql_result($Result,0,"p1");
    $p2 = mysql_result($Result,0,"p2");
    $newPiece = 0; //*default no player
    if($playerId == $p1)
        $newPiece = 1;
    if($playerId == $p2)
        $newPiece = 2;

For some reason when I run the full web app, the pieces still cycle though, even after I deleted the code to make them cycle. Furthermore, after logging in If i manually load the php page in the browser, it modifies the database correctly (where it only plays pieces belonging to that player) and outputs the correct results.

出于某种原因,当我运行完整的 Web 应用程序时,即使我删除了代码以使它们循环,这些片段仍然循环。此外,登录后如果我在浏览器中手动加载 php 页面,它会正确修改数据库(它只播放属于该玩家的作品)并输出正确的结果。

It seems to me that the session is not being carried over when used with Ajax. Yet Google searches tell me that, sessions do work with Ajax.

在我看来,当与 Ajax 一起使用时,会话没有被延续。然而谷歌搜索告诉我,会话确实适用于 Ajax。



更新:我正在尝试提供更多信息。

  1. Logging in works correctly. My ID is recognized and I printed it out next to the board to ensure that I was retrieving it correctly.

  2. The ajax request does update the board. The values passed are correct and confirmed with firebug's console. However instead of placing pieces only for the player they belong to it cycles though the piece states (0,1,2).

  3. When manually browsing to boardUpdate.php and putting in the same values sent from the Ajax the results seen in the echo'ed response indicates that the corresponding piece is played each time as intended.

  4. Same results on my laptop after fresh load of firefox.

  5. Manually browsing to boardUpdate.php without logging in before hand leave the board unchanged (as intended when no user is found in the session).

  6. I've double checked the that session_start() is on the php files and double checked the session ID variables.

  1. 登录工作正常。我的 ID 被识别,我将它打印在板旁边以确保我正确检索它。

  2. ajax 请求确实更新了板子。传递的值是正确的,并通过 firebug 的控制台确认。然而,不是只为他们所属的玩家放置棋子,而是通过棋子状态(0,1,2)循环。

  3. 当手动浏览 boardUpdate.php 并放入从 Ajax 发送的相同值时,回显响应中看到的结果表明每次都按预期播放相应的片段。

  4. 新加载 Firefox 后,我的笔记本电脑上的结果相同。

  5. 手动浏览 boardUpdate.php 而不事先登录,保持董事会不变(当在会话中找不到用户时,这是预期的)。

  6. 我已经仔细检查了 php 文件中的 session_start() 并仔细检查了会话 ID 变量。

Hope this extra information helps, i'm running out of ideas what to tell you. Should I load up the full code?

希望这些额外的信息有帮助,我已经没有想法要告诉你什么了。我应该加载完整的代码吗?



更新 2:

After checking the Ajax responce in fire-bug I realized that the 'play' request does not get a result, and the board is not updated till the next 'update'. I'm still looking into this but I'll post it here for you guys too.

在检查了 fire-bug 中的 Ajax 响应后,我意识到“播放”请求没有得到结果,并且直到下一次“更新”才会更新板。我还在研究这个,但我也会把它贴在这里给你们。

boardUpdate.phpNotable places are: Refresh Board(line6) Place Piece(line20) function boardUpdate($turnCount) (line63)

boardUpdate.php值得注意的地方有: Refresh Board(line6) Place Piece(line20) function boardUpdate($turnCount) (line63)

<?php
session_start();
require '../../omok/dbConnect.php';

    //*** Refresh Board ***
    if(isset($_GET['update']))
    {
        $bid = $_GET['bid'];
        $Query=("SELECT turn FROM board WHERE bid=$bid");
        $Result=mysql_query($Query);
        $turnCount=mysql_result($Result,0,"turn");

        if($_GET['turnCount'] < $turnCount) //** Turn increased
        {
            boardUpdate($turnCount);
        }
    }

    //*** Place Piece ***
    if(isset($_GET['play'])) // turn order? player detect?
    {
        $squareID = $_GET['play'];
        $bid = $_GET['bid'];

        $Query=("SELECT turn, boardstate FROM board WHERE bid=$bid");
        $Result=mysql_query($Query);
        $turnCount=mysql_result($Result,0,"turn");
        $boardState=mysql_result($Result,0,"boardstate");

        $turnCount++;

        $playerId = $_SESSION['char'];
        $Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
        $Result=mysql_query($Query);
        $p1 = mysql_result($Result,0,"p1");
        $p2 = mysql_result($Result,0,"p2");
        $newPiece = 0; //*default no player
        if($playerId == $p1)
            $newPiece = 1;
        if($playerId == $p2)
            $newPiece = 2;

//      if($newPiece != 0)
//      {
            $oldPiece = getBoardSpot($squareID, $bid);
            $oldLetter = $boardState{floor($squareID/3)};
            $slot = $squareID%3;

            //***function updateCode($old, $new, $current, $slot)***
            $newLetter = updateCode($oldPiece, $newPiece, $oldLetter, $slot);
            $newLetter = value2Letter($newLetter);
            $newBoard = substr_replace($boardState, $newLetter, floor($squareID/3), 1);

            //** Update Query for boardstate & turn
            $Query=("UPDATE board SET boardState = '$newBoard', turn = '$turnCount' WHERE bid = '$bid'");
            mysql_query($Query);
//      }
        boardUpdate($turnCount);


    }

    function boardUpdate($turnCount)
    {
            $json = '{"turnCount":"'.$turnCount.'",';           //** turnCount **


            $bid = $_GET['bid'];
            $Query=("SELECT boardstate FROM board WHERE bid='$bid'");
            $Result=mysql_query($Query);
            $Board=mysql_result($Result,0,"boardstate");
            $json.= '"boardState":"'.$Board.'"';            //** boardState **


            $json.= '}';
            echo $json;
    }

    function letter2Value($input)
    {
        if(ord($input) >= 48 && ord($input) <= 57)
            return ord($input) - 48;
        else
            return ord($input) - 87;
    }

    function value2Letter($input)
    {
        if($input >= 10)
            return chr($input += 87);
        else
            return chr($input += 48);
    }


    //*** UPDATE CODE *** updates an letter with a new peice change and returns result letter.
    //***** $old : peice value before update
    //***** $new : peice value after update
    //***** $current : letterValue of code before update.
    //***** $slot : which of the 3 sqaures the change needs to take place in.
    function updateCode($old, $new, $current, $slot)
    {
        if($slot == 0)
        {// echo $current,"+((",$new,"-",$old,")*9)";
            return letter2Value($current)+(($new-$old)*9);
        }
        else if($slot == 1)
        {// echo $current,"+((",$new,"-",$old,")*3)";
            return letter2Value($current)+(($new-$old)*3);
        }
        else //slot == 2
        {// echo $current,"+((",$new,"-",$old,")";
            return letter2Value($current)+($new-$old);
        }
    }//updateCode()


    //**** GETBOARDSPOT *** Returns the peice value at defined location on the board.
    //****** 0 is first sqaure increment +1 in reading order (0-254).
    function getBoardSpot($squareID, $bid)
    {
        $Query=("SELECT boardstate FROM board WHERE bid='$bid'");
        $Result=mysql_query($Query);
        $Board=mysql_result($Result,0,"boardstate");


        if($squareID %3 == 2) //**3rd spot**
        {
            if( letter2Value($Board{floor($squareID/3)} ) % 3 == 0)
                return 0;
            else if( letter2Value($Board{floor($squareID/3)} ) % 3 == 1)
                return 1;
            else
                return 2;
        }
        else if($squareID %3 == 0) //**1st spot**
        {
            if(letter2Value($Board{floor($squareID/3)} ) <= 8)
                return 0;
            else if(letter2Value($Board{floor($squareID/3)} ) >= 18)
                return 2;
            else
                return 1;
        }
        else //**2nd spot**
        {
            return floor(letter2Value($Board{floor($squareID/3)}))/3%3;
        }
    }//end getBoardSpot()


?>



请帮忙,如果需要,我很乐意提供更多信息。提前致谢 =)

回答by davidtbernal

From the small snippet of code we have, it's difficult to tell what your problem might be. What I can say is that session_startshould be one of the first things you do on each page where you're expecting to use the session. After that, I would just immediately do a var_dumpof $_SESSIONto see that the data is in there (put a dieright after that). It is quite possible that your true problem lies somewhere else, and that the session is in fact working. Is there a problem with your login code, for example, that is causing it to wipe out the session?

从我们拥有的一小段代码中,很难判断您的问题可能是什么。我可以说的是,这session_start应该是您在希望使用会话的每个页面上做的第一件事。在那之后,我会立即执行 a var_dumpof$_SESSION以查看数据在那里(die在此之后放一个)。您的真正问题很可能出在其他地方,而会话实际上正在运行。例如,您的登录代码是否有问题导致它清除会话?

You can use Firebugto look at the raw results of your AJAX calls, which should be helpful, since your script appears to work if you directly visit the page.

您可以使用Firebug查看 AJAX 调用的原始结果,这应该会有所帮助,因为如果您直接访问该页面,您的脚本似乎可以正常工作。

Cases where I've seen sessions not work as expected have generally been that session_startis being called too often or too late. The other possibility is that you have an insanely short timeout, but that sounds unlikely.

我看到会话没有按预期工作的情况通常session_start是调用太频繁或太晚。另一种可能性是您的超时时间非常短,但这听起来不太可能。

Finally, you can make sure that your PHP install is set to use cookie sessions. It's very unlikely at this point that it wouldn't be, but you could look.

最后,您可以确保您的 PHP 安装设置为使用 cookie 会话。在这一点上不太可能不会,但你可以看看。

回答by Kobi

One potential problem in this code is the use of $.get- it is cached by IE, so your server code doesn't run every time. Try using $.ajaxwith cache set to false:

此代码中的一个潜在问题是使用$.get- 它由 IE 缓存,因此您的服务器代码不会每次都运行。尝试使用$.ajax缓存设置为 false:

$.ajax({
  type: 'GET',
  url: 'includes/boardControl.php',
  cache: false,
  data: {play: value, bid: bid}
});