如何将javascript值与php值组合到单个javascript变量中?

时间:2013-10-20 02:11:32

标签: javascript php variables return-value

我在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>

1 个答案:

答案 0 :(得分: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代码