如何将php中的javascript变量传递回javascript

时间:2015-03-27 15:15:31

标签: javascript php html variables increment

我有一个带有javascript变量的html脚本,这个变量我已经传递给一个php文件,将它递增1.我的问题是我不知道怎么会把它传回给html文件,然后显示它,我也不知道变量如何在网站上工作,如果我必须以某种方式保存变量,以确保它是与我离开网站时相同的更新变量。

html脚本:

<script type="text/javascript">

                var nrVar= 1;
                document.getElementById("nrVar").innerHTML = nrVar;
                document.getElementByID("nrVar").value = nrVar;

</script>

php脚本:

    <?php 

    $nrVar= $_POST['nrVar'];

    $nrVar= round((int)$nrVar+1);

?>

2 个答案:

答案 0 :(得分:1)

您必须在表单字段中保存您的javascript编号,将表单发送到PHP脚本,数字会增加,然后在会话中将其发回。接下来是代码:

<强> increase1.php

<?php
// GET THE NUMBER FROM PHP. THE FIRST TIME IT'S JUST 1. NEXT TIMES
// THE NUMBER COMES IN SESSION INCREASED FROM PHP SCRIPT.
session_start();
if ( IsSet( $_SESSION["increased"] ) )
     $increased = (int)$_SESSION["increased"];
else $increased = 1;
?>
<html>
  <head>
    <title>Jose Manuel Abarca Rodriguez</title>
    <script type="text/javascript">

// ASSIGN VALUE TO JAVASCRIPT VARIABLE.
var my_number = <?php echo $increased; ?>;

// SEND THE FORM TO INCREASE2.PHP.
function clik () {
document.getElementById("the_number").value = my_number;
document.getElementById("frm").submit();
}
    </script>
  </head>
  <body>
    My number is = <script type="text/javascript">document.write( my_number );</script>
    <br/>
    <button onclick="clik()">Increase my number</button>

<!-- FORM TO SEND NUMBER TO PHP. -->
    <form method="post" action="increase2.php" 
          id="frm" style="display:none">
      <input type="text" id="the_number" name="the_number"/>
    </form>

  </body>
</html>

<强> increase2.php

<?php
session_start();
$num = (int)$_POST["the_number"];
$_SESSION["increased"] = ++$num; // !!! NEVER $num++ !!!
header("Location: increase1.php" ); // BACK TO FIRST PAGE.
?>

创建两个具有给定名称的文本文件(increase1.php和increase2.php),打开浏览器并运行localhost / increase1.php。

答案 1 :(得分:0)

假设$ _POST是由普通提交而不是AJAX请求发送的。我会使用PHP生成脚本以及网站的其余部分来定义变量值:

<script>
var nrVar = parseInt('<?php echo $_POST['nrVar']; ?>');
</script>

parseInt这里是为了确保我们得到整数值,$ _POST清理也可以直接阻止xss甚至javascript注入。