[英]Javascript global scope variables accessed later in a script tag with src
I want to be able to pass variables from php into my javascript code in order to save a given users high score.我希望能够将变量从 php 传递到我的 javascript 代码中,以保存给定用户的高分。 I have done that successfully by at the top of my page by declaring:
我通过在页面顶部声明成功地做到了这一点:
<?php
session_start();
$bricks = $_SESSION["bricks"];
require 'includes/dbh.inc.php';
require 'save.php';
?>
SESSION['bricks'] is the high-score in the database. SESSION['bricks'] 是数据库中的高分。 A the end of of the html code within the php code I have my entire game written within a script tag.
php 代码中 html 代码的结尾我将整个游戏写在一个脚本标签中。 In the game
在游戏里
this.highScore = "<?php echo $bricks?>";
But this is long and messy.但这是漫长而混乱的。 Lets say I wanted to replace the long script tag with a
<script src="myGame.js"></script>
this would be problematic because the file would no longer be a php file and would not be able to grab the session variable bricks.假设我想用
<script src="myGame.js"></script>
替换长脚本标记,这将是有问题的,因为该文件将不再是一个 php 文件并且无法获取会话变量砖块。
When using the global scope I can grab the variable highscore from the session variable使用全局范围时,我可以从会话变量中获取变量 highscore
<script> var highScore = <?php echo $bricks;?>;</script>
then later:后来:
<script>console.log(highScore)</script>
but if I make the second script tag link to a source:但是如果我将第二个脚本标记链接到源:
<script src="myGame.js"></script>
I will not be able to access that variable highScore in myGame.js.我将无法在 myGame.js 中访问该变量 highScore。 Is there a way to pass a variable from a script tag at the top of your page into a script tag with an src attribute and access that variable within the javascript document that is linked?
有没有办法将页面顶部的脚本标记中的变量传递到具有 src 属性的脚本标记中,并在链接的 javascript 文档中访问该变量? there is a workaround, but I want to know if I can make it more manageable this way.
有一个解决方法,但我想知道我是否可以通过这种方式使其更易于管理。
First make your js code stable:首先让你的js代码稳定:
var highScore = parseInt("<?php echo $bricks;?>");
In your javascript object
try set global variable highScore to object's property :在您的 javascript
object
尝试将全局变量 highScore 设置为对象的属性:
this.highScore = highScore;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.