如何将javascript变量从php传递回javascript [英] How to pass a javascript variable from php back to javascript

查看:65
本文介绍了如何将javascript变量从php传递回javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a html script with a javascript variable inside it, this variable I have then passed to a php file, to increment it by 1. My problem is that I don't know how I would then pass it back to the html file, to then display it, also I don't know how the variables work on a website, if I have to save the variable in some sort of way to make sure it is the same updated variable as when I left the site.

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);

?>

推荐答案

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

You have to save your javascript number in a form field, send the form to a PHP script, there the number is increased, then send it back in session. Next is the code :

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和gain2.php),打开浏览器并运行localhost/increase1.php.

Create two textfiles with the given names (increase1.php and increase2.php), open your browser and run localhost/increase1.php.

这篇关于如何将javascript变量从php传递回javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆