如何将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.