如何将javascript变量从php传递回javascript

编程入门 行业动态 更新时间:2024-10-10 23:19:50
本文介绍了如何将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

本文发布于:2023-11-24 22:07:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   javascript   php

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!