从 PHP 访问 JavaScript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2338942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access a JavaScript variable from PHP
提问by Chris Armstrong
I need to access a JavaScriptvariable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
我需要使用PHP访问JavaScript变量。这是我目前正在尝试的代码的精简版本,它不起作用:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
我是 JavaScript 和 PHP 的新手,所以我真的很感激任何建议。
UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?
更新:好的,我想我简化了太多。我想要做的是创建一个表单,在提交时更新 Twitter 状态。我的表单工作正常,但我还想添加地理定位数据。由于我使用 Javascript(特别是 Google Geolocation API)来获取位置,因此在提交表单时如何使用 PHP 访问该信息?
回答by Pandincus
The short answer is you can't.
简短的回答是你不能。
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
我不知道任何 PHP 语法,但我可以告诉你的是,PHP 在服务器上执行,而 JavaScript 在客户端(在浏览器上)执行。
You're doing a $_GET, which is used to retrieve form values:
您正在执行 $_GET,用于检索表单值:
The built-in $_GET function is used to collect values in a form with method="get".
内置的 $_GET 函数用于以 method="get" 的形式收集值。
In other words, if on your page you had:
换句话说,如果您的页面上有:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
您的 $_GET 调用将检索该输入字段中的值。
So how to retrieve a value from JavaScript?
那么如何从 JavaScript 中检索一个值呢?
Well, you could stick the javascript value in a hidden form field...
好吧,您可以将 javascript 值粘贴在隐藏的表单字段中...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
然后,当用户单击您的提交按钮时,他/她将向 blah.php 发出“GET”请求,并发送“test”中的值。
回答by Decipher
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
由于 JavaScript 是一种客户端语言而 PHP 是一种服务器端语言,您需要将变量物理推送到 PHP 脚本,方法是在 PHP 脚本的页面加载中包含变量 (script.php?var=test ),这实际上与 JavaScript 无关,或者每次更改变量时通过 AJAX/AHAH 调用将变量传递给 PHP。
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
如果你确实想走第二条路,你会看看 XMLHttpRequest,或者我的偏好,jQuerys Ajax 调用:http://docs.jquery.com/Ajax
回答by Hawkcannon
If showing data to the user, do a redirect:
如果向用户显示数据,请执行重定向:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
或 iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
如果您不需要用户输出,请创建一个宽度=0 和高度=0 的 iframe。
回答by Matthew Flaschen
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
_GET 访问查询字符串变量,test 不是查询字符串变量(PHP 不以任何方式处理 JS)。你需要重新思考。您可以创建一个 php 变量 $test,然后执行以下操作:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
当然,我不知道你为什么想要这个,所以我不确定最好的解决方案。
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
编辑:正如其他人所指出的,如果 JavaScript 变量确实是在客户端上生成的,则您将需要 AJAX 或表单将其发送到服务器。
回答by cosphi
try adding this to your js function:
尝试将其添加到您的 js 函数中:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
稍后在 html 中:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.
此 div 将包含要通过表单传递到另一个 js 函数或 php 的 js var,请记住将其放置在您的 html 表单中!。这个解决方案对我来说很好。
In your specific geolocation case you can try adding the following to function showPosition(position):
在您的特定地理位置情况下,您可以尝试将以下内容添加到函数 showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
稍后将这些 div 添加到您的 html 表单中:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
在这些 div 中,您将获得纬度和经度作为 php 表单的输入值,您最好使用 css 隐藏它们(如果使用,只显示地图上的标记),以避免用户在提交之前更改它们,并设置您的数据库接受长度为 10,7 的浮点值。
Hope this will help.
希望这会有所帮助。
回答by kyle
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
那么 GET 的问题是,如果用户有一些知识,他可以自己更改值。我写这个是为了让 PHP 能够从 Javascript 中检索时区:
// -- index.php
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
回答by Robin Joy Wirth
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
我正在看这个并在想,如果你只能在表单中将变量输入 php,为什么不制作一个表单并在其中放置一个隐藏的输入,这样它就不会显示在屏幕上,然后将值从你的 javascript 到隐藏的输入和 POST 到 php?它肯定会比其他一些东西少很多麻烦,对吗?

