从PHP访问JavaScript变量 [英] Access a JavaScript variable from PHP
问题描述
我需要使用 PHP 访问 JavaScript 变量。这是我正在尝试的代码的精简版本,它无法正常工作:
I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
我对JavaScript和PHP都是全新的,所以我非常感谢任何建议。
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
更新:好的,我想我简化了太多。我要做的是创建一个表单,在提交时更新Twitter状态。我的表单工作正常,但我还要添加地理位置数据。由于我使用Javascript(特别是Google Geolocation API)来获取位置,在提交表单时如何使用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?
推荐答案
简短的回答是你不能。
我不知道任何PHP语法,但我可以告诉你的是,PHP在服务器上执行,JavaScript在客户端上执行(在浏览器上)。
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).
你正在做$ _GET,用于检索表单值:
You're doing a $_GET, which is used to retrieve form values:
内置$ _GET函数用于使用method =get收集表单中的值。
The built-in $_GET function is used to collect values in a form with method="get".
换句话说,如果你的页面上有:
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
您的$ _GET调用将检索该输入字段中的值。
Your $_GET call would retrieve the value in that input field.
那么如何从JavaScript中检索一个值?
So how to retrieve a value from JavaScript?
好吧,你可以将javascript值粘贴在隐藏的表单字段中......
Well, you could stick the javascript value in a hidden form field...
<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>
然后,当用户点击您的提交按钮时,他/她将发出GET请求到blah.php,发送'test'中的值。
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'.
这篇关于从PHP访问JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!