How to pass a javascript variable from php back to javascript

◇◆丶佛笑我妖孽 提交于 2019-12-11 09:08:20

问题


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:

<script type="text/javascript">

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

</script>

php script:

    <?php 

    $nrVar= $_POST['nrVar'];

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

?>

回答1:


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.
?>

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




回答2:


Assuming that $_POST is sent by a normal submit and not a AJAX request. I would generate script along with rest of the site using PHP to define variable value:

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

parseInt here is to make sure we get integer value, $_POST sanitization would also be good idea to prevent xss or even javascript injection directly.



来源:https://stackoverflow.com/questions/29304105/how-to-pass-a-javascript-variable-from-php-back-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!