【问题标题】:Ajax, JavaScript, PHP/HTML and variablesAjax、JavaScript、PHP/HTML 和变量
【发布时间】:2012-07-13 13:50:24
【问题描述】:

好的...所以我正在开发一款游戏,但我认为我遇到了范围问题...

它从我的 js 文件开始,通过点击玩家想要玩的卡触发:

It starts in my js file:

function playCard(playerId, card){
    $.post("support_files/Blades_functions.php", {
        method:'playCardFromHand',
        playerID:playerId,
    cardName:card
    },function(data){       
        var attr = new Array();
        attr = data.split("/");
        alert(data);
        $("#playerAttackPower").html(attr[0]);
        $("#playerDefensePower").html(attr[1]);
        $("#playerHealth").html(attr[2]);
        $("#playerAttackMod").html(attr[3]);
        $("#playerChargeCounters").html(attr[4]);
        $("#playerSpecialAttackCounters").html(attr[5]);
    });
}

然后进入我的php文件

function playCardFromHand(){
    $weapons = new WeaponCards(); // this is basically a class with variables(card objects) (my answer to php not having enums really)
    $player = $theGame->gamePlayers[$_POST['playerID']]; // this is the variable ($theGame) that I declare in my main php file with all the markup on it. I'm including my functions file in my main file so the variable should be visible... I've tried using "global" keyword as well and that didn't do anything different...       
    $cardName = $_POST['cardName'];
    $card = $weapons->$cardName;
    $card->applyCard($player);      
    echo $player->getAttack()."/".$player->getDefense()."/".$player->getLife()."/".$player->getAttackMultiplier()."/".$player->getChargeCounters()."/".$player->getSpecAttackCounters();
}

所以我的问题是 $player 变量为空,所以没有显示任何内容。基本上,正如您在 js 函数的回调中看到的那样,我只是解析字符串并更新主 php 页面上的播放器统计信息。那么这是一个范围的事情吗?有没有办法让 PHP 持久化 $theGame 变量,它本身就是一个对象,以便我可以在我的函数文件中访问/修改它?

任何想法都会很有帮助...正如我所说的,我已经尝试使用 global 关键字...尝试将 $theGame 对象中的变量公开,尝试将它们设为私有并使用 getter 和 setter...实际上,我有一个单独的问题,似乎无法让我的函数在我的对象上工作,只是将我的变量公开并直接访问它们,而不是使用 getter 和 setter。反正。请帮忙!我好沮丧!!!哈哈

谢谢, 乔恩

【问题讨论】:

  • 你的 $_POST['playerID'] 在 php 文件中有值吗?如果你回应它,它会发出警报吗?
  • 如果我理解的问题是正确的,JS 在很大程度上与这个问题无关。你的问题是 PHP var 没有被持久化......是吗?
  • 是的,Utkanos,这是正确的。 JS 就是逻辑到达那里的方式......所以,对不起。猜猜它并不真的需要在那里,哈哈。
  • the_red_baron:我不确定。我的服务器显然已关闭,因此我无法再次测试该理论以确定,但是当我在将某些内容加载到主文件中的数组之前进行处理时,然后在函数中将播放器加载到其中,长度为1 所以我认为你的问题的答案是否定的......
  • 好的 red_baron。服务器恢复了,我对其进行了测试。这是肯定的。即使我将玩家加载到 $theGame->gamePlayers 中,当我调用该函数时它也不会显示...

标签: php javascript ajax scope


【解决方案1】:

确保将 PHP 变量声明为全局变量,否则必须在函数内部获取 POST 变量。

【讨论】:

  • 之前尝试过,如果我声明它是全局的并没有什么不同......仍然不会出现。然而我又试了一次,还是没有成功。这是我声明它的方式: global $theGame; $theGame = 新游戏(); $theGame->gamePlayers[0] = new Player("Jon", "Male", "Rogue");
  • 在 playCardFromHand 函数的顶部将 $theGame 变量声明为全局变量。
  • 没用。仅在顶部的函数文件和首先设置播放器的函数中尝试过...没有骰子...
  • 好的,所以我在 PHP 中使用 JSON 对象传递到 JavaScript 端,并且能够以这种方式更新我的统计信息......但我看不到获取对象的方法在我的 ajax 调用的回调中回到 PHP...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2019-11-16
  • 2013-01-21
相关资源
最近更新 更多