从 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.
UPDATE:好的,我想我把它简化了太多.我想要做的是创建一个表单,在提交时更新 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>
然后,当用户单击您的提交按钮时,他/她将向 blah.php 发出GET"请求,并发送 '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屋!