简体   繁体   English

将JavaScript变量传递给php?

[英]Passing javascript variables to php?

ok so im trying to get a javascript variable into a php script, this would be an example, 好的,所以我试图将javascript变量导入php脚本,这将是一个示例,

<script type="text/javascript">
x = new Date()
</script>
<?php
$x = $_GET["x"]; 
?>
<p><?php echo $x ?></p>

i just cant get it to work! 我只是不能让它工作! I need help please? 我需要帮助吗?

EDIT: well im just trying to get the hash from a url via javascript then put that in a php script. 编辑:嗯,我只是想通过JavaScript从URL中获取哈希值,然后将其放入php脚本中。

PHP and javascript don't work like that. PHP和javascript不能那样工作。

PHP is a server-side language. PHP是一种服务器端语言。 While javascript is a clientside language. 而javascript是一种客户端语言。

There are still ways of passing data from the client-window to your server, via ajax, query parameters, cookies... But none will work in the same page. 仍然存在通过ajax,查询参数,cookie将数据从客户端窗口传递到服务器的方法,但是在同一页面上将无法使用。

Give us a clearer image on what you are trying to achieve and we will gladly help. 让我们对您要实现的目标有更清晰的了解,我们将竭诚为您服务。

UPDATE 更新

JS JS

<script type="text/javascript">  
    document.cookie = 'name=Khez' ;  
</script>  

PHP 的PHP

<?php  
    var_dump($_COOKIE['name']);  
?>  

So there are 2 pages page1.php and page2.php 因此,共有2页page1.phppage2.php

page2.php needs to pass JS variables to page1.php page2.php需要将JS变量传递给page1.php

We can do this by passing it as url variables from page2.php and get it in page1.php using $_GET[] . 我们可以通过将其作为page2.php url变量page2.php并使用$_GET[]将其获取到page1.php来实现。

page2.php (send JS variable) page2.php (发送JS变量)

<script type=text/javascript>
  var lati = location.lat();
  var longi = location.lng();
  document.location = 'http://www.rajak.me/index.php?addlat='+lati+'&addlong='+longi;   
});
</script>

page1.php (receive JS variable) page1.php (接收JS变量)

<?php    
  $addlat = $_GET['addlat'];
  $addlong = $_GET['addlong'];
?>

You could use the following Javascript which will link to somepage.php with the variable in the Url 您可以使用以下Javascript将其与Url中的变量链接到somepage.php

<script type="text/javascript">
x = new Date()
window.location.href = "somepage.php?w1=" + x;
</script>

This is the contents of somepage.php which recieves the variable and echoes it 这是somepage.php的内容,该内容接收变量并回显它

<?php
   if (isset($_GET["w1"])) {
     $x = $_GET["w1"];
     echo $x;
   }else{
   echo 'no variable received';
   }
    ?>

PHP is "Server Side" code and javascript is client side code. PHP是“服务器端”代码,而javascript是客户端代码。 They don't interact... 他们不互动...

PHP is server-side~ all parsing is done on the server. PHP是服务器端的〜所有解析都在服务器上完成。 JavaScript is client-side~ everything happens AFTER it get's to the client. JavaScript是客户端的〜发生在客户端之后的所有事情。 If you need date in PHP, I recommend time() and or date() 如果您需要PHP中的日期,建议使用time()和or date()

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

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