在html页面中传递javascript值并将其放入php变量[duplicate]
Possible Duplicate:
How to pass JS variable to php?
pass a js variable to a php variable
I'm passing a javascript from a script to an html page using document.getElementById.innerHTML
. The value is printed out correctly in my html page...Now I would know it is possible take this value print in html page and (always in the same page) put it in a php variable?
可能重复: strong>
如何将JS变量传递给php?
将js变量传递给php变量 p> blockquote >我正在使用
document.getElementById.innerHTML code>将javascript从脚本传递到html页面。 该值在我的html页面中正确打印出来......现在我知道可以在html页面中打印此值并且(总是在同一页面中)将其放入php变量中吗? p> DIV>
Create a hidden variable like this
<form method="post">
<input type="hidden" name="hiddenField" id="hiddenField"/>
</form>
in Javascript set value for that variable
document.getElementById("hiddenField").value=6;
in PHP
$value=$_POST['hiddenField'];
If you want to call back to a PHP script from your page, you'll have to look into XMLHttpRequest (or a wrapper library such as jQuery).
After you see a page, the php script finished, so you can only send a var via Ajax to your php file and run the script again.
one easy way to use ajax is jquery
I can think of two ways to do this:
Use an XMLHttpRequest object to send an asynchronous request to some PHP page which records this value.
On the php [holdvalue.php] side:
<?php
$myval = $_GET['sentval'];
// Do something with $myval
?>
On the JavaScript side:
var x = 34; //Some interesting value
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "holdvalue.php/?sentval=" + x, true);
xmlhttp.send();
OR, Use a hidden form field. On the HTML side:
<form id="sendform" method="get" action="holdvalue.php">
<input type="hidden" id="sentval" />
<input type="submit" />
</form>
And on the JS side: document.getElementById("sentval").value = x; // Either the following or send it whenever the user submits the form: document.getElementById("sendform").submit();