2012-04-23 281 views
1

我有一个index.php文件,我有帆布游戏。这个游戏从单独的game.js文件中加载,其中我有变量:ballsCought。我希望这可靠和名字inputet文本输入传递点击另一个PHP文件。我的代码:将全局javascript变量传递给php

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Simple Canvas Game</title> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script> 
     $(document).ready(function(){ 

      function score(){ 
       $('#score').fadeIn(1000); 
       $('#score').load("load_players.php"); 
      }; 

      setInterval(score , 1000); 

      var nam = $("#name").val();   

      $('#submit').keyup(function(e){ 
       if(e.keyCode == 13){ 
       $.post('upload_score.php','n=' +nam, 'score=' +ballsCought); 
       } 
      }); 

      $('#submit').click(function(e){ 
       $.post('upload_score.php','n=' +nam, 'score=' +ballsCought); 
      }); 

     }); 
    </script> 
</head> 
<script src="game.js"></script> 
<body> 
    <canvas id="canvas" width="525" height="525"></canvas> 
    <br /><p><span id="points"></span><input type="text" id="name" placeholder="Name..."/><input type="submit" id="submit" value="Submit"/></p> 
    <br /><span id="score"></span> 
</body> 
</html> 

但是,这个职位功能不工作任何想法?谢谢你...

+1

为什么不把你的变量的值放在隐藏字段中,然后将该值从隐藏字段传递到你想要的其他页面。 – 2012-04-23 16:29:40

+0

“不工作”是什么意思?你得到什么错误? – j08691 2012-04-23 16:36:14

+0

我试图去做。为了将变量值隐藏起来,但我无法使其工作,但它不会传递。仍然返回0.此代码:$(“#points_hidden”)。html(ballsCaught); points_hidden是隐藏字段,此行位于game.js文件内 – 2012-04-23 17:08:34

回答

1

看起来像你的$ .post方法是不正确的。如果你想将数据传递到PHP页面,你需要使用JavaScript对象符号,像这样:

$.post('upload_score.php', {n: nam, score: ballsCought}); 

你可以阅读更多有关各种方式从jQuery Docs页面调用$。员额现在

您的PHP页面可能仍然存在问题。您应该使用类似Firebug的东西来查看Ajax请求以及可能返回的任何错误。