在html页面中传递javascript值并将其放入php变量中

时间:2012-02-21 11:14:32

标签: php javascript html

  

可能重复:
  How to pass JS variable to php?
  pass a js variable to a php variable

我正在使用document.getElementById.innerHTML将javascript从脚本传递到html页面。这个值在我的html页面中正确打印出来......现在我知道可以在html页面中打印这个值并且(总是在同一页面中)将它放在php变量中吗?

4 个答案:

答案 0 :(得分:5)

像这样创建隐藏变量

<form method="post">
      <input type="hidden" name="hiddenField" id="hiddenField"/>
</form>

在该变量的Javascript设置值

document.getElementById("hiddenField").value=6;
PHP中的

$value=$_POST['hiddenField'];

答案 1 :(得分:0)

如果要从页面回调PHP脚本,则必须查看XMLHttpRequest(或jQuery等包装库)。

http://en.wikipedia.org/wiki/Ajax_%28programming%29

答案 2 :(得分:0)

看到页面后,php脚本完成了,所以你只能通过Ajax将var发送到你的php文件并再次运行脚本。

使用ajax的一种简单方法是jquery

答案 3 :(得分:0)

我可以想到两种方法:

使用XMLHttpRequest对象向某个记录此值的PHP页面发送异步请求。

在php [holdvalue.php]方面:

<?php
    $myval = $_GET['sentval'];
    // Do something with $myval
?>

在JavaScript方面:

var x = 34; //Some interesting value
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "holdvalue.php/?sentval=" + x, true);
xmlhttp.send();

,使用隐藏的表单字段。在HTML方面:

<form id="sendform" method="get" action="holdvalue.php">
 <input type="hidden" id="sentval" />
 <input type="submit" />
</form>

在JS方面:     document.getElementById(“sentval”)。value = x;     //以下内容或在用户提交表单时发送:     的document.getElementById( “sendform”)提交();