【问题标题】:Set the javascript variable in php session variable在 php 会话变量中设置 javascript 变量
【发布时间】:2014-01-23 17:01:24
【问题描述】:

我想根据用户浏览器时间设置php会话$_SESSION['time']

 // gives time difference between utc time and current user local time
var offset = ((new Date().getTimezoneOffset()) * -1) * 60;

我希望将此偏移值存储在会话变量中,例如

$_SESSION['time'] = offset ; // something like this

例子

 <script type="text/javascript">
   I have to set the $SESSION['time'] variable at the beginning of page
   so that i can use it down the dom
 </script>
 <span class="time_stamp"><?php echo $_SESSION['time'];?></span> 

【问题讨论】:

  • 当你想在之后使用 PHP 输出变量时,为什么必须通过 Javascript 设置变量?这从根本上是行不通的。
  • 实际上,var time = '&lt;?php echo $_SESSION['time']; ?&gt;'; 对我有用,但我想这是一个不好的做法?
  • 对不起,我必须从 javascript 设置服务器端会话值
  • 您需要使用ajax 将javascript 值赋给PHP 变量
  • @user2513523 当然可以。请记住 - 根据目的 - 如果需要此时间戳来验证任何特定信息,这是一个安全问题。仅在仅用于本地输出且不希望此时间戳以 Ajax 请求或表单或类似形式回发时才使用它。

标签: javascript php ajax


【解决方案1】:

在服务器上的页面加载时创建一个 php 会话。 因此在页面加载后无法创建会话。

所以如果你不想使用 ajax,你只有 1/2 的解决方案。

解决方案 1

sess.php

<?php
 session_start();
 $_SESSION['time']=$_GET['time'];
?>

js

head.appendChild(document.createElement('script')).src='sess.php?time='+offset;

注意:head 在这种情况下只是一个参考。

但是

这也是异步的。

又是这样。页面加载后无法设置会话。

解决方案 2

使用 gd 预加载 php 输出的图像,该图像也设置为您的会话。 ;)

如果您想知道我如何查看它。(这会导致页面自然加载,并且在 ie6 上也可以正常工作)我只是不记得在正文之前如何预加载图像。


前段时间我也遇到过同样的问题……我用的是 ajax。

function ajax(a,b,c){ // Url, Callback, just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}
function LoadThePage(){
 //just some milliseconds passed.
 //session is set
 //load the rest of your page.
 //MOST OF THE TIME this loads faster than the body does.(window.onload)
}
ajax('sess.php?time='+offset,LoadThePage);

另一方面...现在大多数现代浏览器都支持本地存储。

所有手机和现代浏览器。

如果我存储这样的东西。为什么要使用 php 会话?

localstorage 用于替换它。

window.localStorage['offset']=((new Date().getTimezoneOffset()) * -1) * 60;

【讨论】:

  • 我知道处理会话和 js 是一团糟……会话只适用于“..secure”登录数据。
猜你喜欢
  • 2017-07-08
  • 1970-01-01
  • 2011-04-05
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多