简体   繁体   English

从PHP访问JavaScript变量

[英]Access a JavaScript variable from PHP

I need to access a JavaScript variable with PHP . 我需要使用PHP访问JavaScript变量。 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'];
?>

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. 我正在尝试创建一个表单,该表单在提交时将更新Twitter状态。 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? 由于我使用Javascript(特别是Google Geolocation API)来获取位置,因此提交表单时如何使用PHP访问该信息?

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”中的值。

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

_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). _GET访问查询字符串变量,test不是查询字符串变量(PHP不会以任何方式处理JS)。 You need to rethink. 您需要重新考虑。 You could make a php variable $test, and do something like: 您可以制作一个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或表单将其发送到服务器。

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。

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!. 该div将包含要通过表单传递给另一个js函数或php的js var,请记住将其放在您的html表单中! This solution is working fine for me. 这个解决方案对我来说很好。

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. 希望这会有所帮助。

Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. 嗯,GET的问题在于,如果他有一些知识,则用户可以自己更改值。 I wrote this so that PHP is able to retrive the timezone from Javascript: 我这样做是为了使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']); 
  } 
}
?>

JS ist browser-based, PHP is server-based. JS基于浏览器,PHP是基于服务器的。 You have to generate some browser-based request/signal to get the data from the JS into the PHP. 您必须生成一些基于浏览器的请求/信号,才能将数据从JS导入PHP。 Take a look into Ajax . 看一看Ajax

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? 我正在考虑这一点,并在想,如果您只能以表单的形式将变量放入php中,为什么不只创建表单并将隐藏的输入内容放到东西中,这样它就不会显示在屏幕上,然后将其值您的JavaScript到隐藏的输入和POST到PHP的? It would sure be a lot less hassle than some of this other stuff right? 肯定会比其他一些事情少很多麻烦吧?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM