我需要使用 PHP 访问 JavaScript 变量。这是我目前正在尝试的代码的精简版本,但它不起作用:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
我是 JavaScript 和 PHP 的新手,所以我非常感谢任何建议。
更新:好的,我想我简化得太多了。我要做的是创建一个表单,在提交时更新 Twitter 状态。我的表单工作正常,但我还想添加地理位置数据。由于我使用 Javascript(特别是 Google Geolocation API)来获取位置,因此在提交表单时如何使用 PHP 访问该信息?
最佳答案
简短的回答是你不能。
我不知道任何 PHP 语法,但我可以告诉你的是,PHP 是在服务器上执行的,而 JavaScript 是在客户端(在浏览器上)执行的。
您正在执行 $_GET,它用于 retrieve form values :
The built-in $_GET function is used to collect values in a form with method="get".
换句话说,如果您的页面上有:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
您的 $_GET 调用将检索该输入字段中的值。
那么如何从 JavaScript 中获取值呢?
好吧,您可以将 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>
然后,当用户单击您的提交按钮时,他/她将向 blah.php 发出“GET”请求,并发送 'test' 中的值。
关于php - 从 PHP 访问 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2338942/