0

我在 php 中有一个数字,即25.

然后,我有一个 javascript 变量,它是一个数字;即57

php 编号是从这样的文本文件中提取的:

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

javascript是这样的:

/* 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

现在,我想将这两个数字组合成一个 javascript 变量。

所以我写了这个javascript:

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

看看它是否有效:

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

我试过了,但是返回的值是“NaN”,这意味着它不起作用。

那么我怎样才能让它工作呢?


更新:

我得到它的工作!我不确定我一开始做错了什么,因为我一直在尝试一些东西,直到它奏效。

这是工作代码(这是 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>
4

1 回答 1

0

由于每个人都想发表评论但没有给出实际答案,因此我将在解决问题后发布我自己问题的答案:

这是工作代码(这是 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>

所以显然可以javascript 中包含 php 代码。

于 2013-10-20T02:50:50.150 回答