简体   繁体   中英

How to combine a javascript value with a php value to a single javascript variable?

I have a number in php, ie 25 .

Then, I have a javascript variable which is a number; ie 57 .

The php number is extracted from a text file like this:

<!-- NOTE: for this example, the value in file.txt is the number 25 -->
<?php 
$the_number = file_get_contents("file.txt");
?>

And the javascript is like this:

/* first let's define "$a_variable_from_somewhere_that_is_a_number" so it helps you understand this question: */
var $a_variable_from_somewhere_that_is_a_number = 57;

/* ok and here is the javascript */
var another_number = $a_variable_from_somewhere_that_is_a_number

Now, I want to combine these two numbers into a single javascript variable.

So I write this javascript:

var php_number = parseInt(<?= $the_number ?>);
var javascript_number = parseInt(another_number);
var combined_number = php_number + javascript_number;

And to see if it worked:

Did it work? <script type="text/javascript">document.write(combined_number);</script>

I tried it, but the value is returned as "NaN", meaning it didn't work.

So how can I get it to work?


UPDATE:

I got it working!! I'm not sure what I did wrong at first because I kept trying stuff until it worked.

Here is the working code (this is the full contents of test-page.php) :

<?php
$the_number = file_get_contents("count.txt");
?>

PHP Number: <?= $the_number ?>

<script type="text/javascript">
    $a_variable_from_somewhere_that_is_a_number = 25;
    var another_number = $a_variable_from_somewhere_that_is_a_number

    var php_number = parseInt(<?= $the_number ?>);
    var javascript_number = parseInt(another_number);
    var combined_number = php_number + javascript_number;
</script>

<br /><br />
Did it work? <script type="text/javascript">document.write(combined_number);</script>

Since everyone wants to leave a comment but not give an actual answer, I'll just post the answer to my own question since I solved it:

Here is the working code (this is the full contents of test-page.php) :

<?php
$the_number = file_get_contents("count.txt");
?>

PHP Number: <?= $the_number ?>

<script type="text/javascript">
    $a_variable_from_somewhere_that_is_a_number = 25;
    var another_number = $a_variable_from_somewhere_that_is_a_number

    var php_number = parseInt(<?= $the_number ?>);
    var javascript_number = parseInt(another_number);
    var combined_number = php_number + javascript_number;
</script>

<br /><br />
Did it work? <script type="text/javascript">document.write(combined_number);</script>

So apparently it is possible to include php code within javascript.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM