I want to be able to pass variables from php into my javascript code in order to save a given users high score. 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. A the end of of the html code within the php code I have my entire game written within a script tag. 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.
When using the global scope I can grab the variable highscore from the session variable
<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. 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? there is a workaround, but I want to know if I can make it more manageable this way.
First make your js code stable:
var highScore = parseInt("<?php echo $bricks;?>");
In your javascript object
try set global variable highScore to object's property :
this.highScore = highScore;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.