从PHP访问一个JavaScript变量

时间:2022-08-27 17:38:15

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:

我需要用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(尤其是谷歌地理定位API)来获取位置,所以当我提交表单时如何使用PHP访问这些信息?

7 个解决方案

#1


32  

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函数用于以方法=“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'.

然后,当用户单击您的submit按钮时,他/她将向blah发出“GET”请求。php,在“test”中发送值。

#2


4  

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 =测试),这与JavaScript无关,或通过变量通过AJAX / 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

#3


2  

_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不是一个querystring变量(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或表单将其发送到服务器。

#4


2  

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。

#5


2  

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 var以通过表单传递给另一个js函数或php,记住将其放入html表单中!这个解决方案对我来说很有效。

In your specific geolocation case you can try adding the following to function showPosition(position):

在特定的地理定位情况下,您可以尝试在函数showPosition(位置)中添加以下内容:

    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.

希望这将帮助。

#6


1  

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']); 
  } 
}
?>

#7


0  

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

基于浏览器的PHP是基于服务器的。您必须生成一些基于浏览器的请求/信号,以便从JS中获取数据到PHP中。看看Ajax。

#1


32  

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函数用于以方法=“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'.

然后,当用户单击您的submit按钮时,他/她将向blah发出“GET”请求。php,在“test”中发送值。

#2


4  

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 =测试),这与JavaScript无关,或通过变量通过AJAX / 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

#3


2  

_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不是一个querystring变量(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或表单将其发送到服务器。

#4


2  

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。

#5


2  

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 var以通过表单传递给另一个js函数或php,记住将其放入html表单中!这个解决方案对我来说很有效。

In your specific geolocation case you can try adding the following to function showPosition(position):

在特定的地理定位情况下,您可以尝试在函数showPosition(位置)中添加以下内容:

    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.

希望这将帮助。

#6


1  

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']); 
  } 
}
?>

#7


0  

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

基于浏览器的PHP是基于服务器的。您必须生成一些基于浏览器的请求/信号,以便从JS中获取数据到PHP中。看看Ajax。