在php会话变量中设置javascript变量 [英] Set the javascript variable in php session variable
问题描述
我想基于用户浏览器时间设置php会话 $ _ SESSION ['time']
I want to set the php session $_SESSION['time']
based on user browser time
// gives time difference between utc time and current user local time
var offset = ((new Date().getTimezoneOffset()) * -1) * 60;
我希望将此偏移值存储在会话变量中,例如
I want this offset value to be stored in a session variable like
$_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会话.因此,无法在页面加载后创建会话.
A php session is created at the page load on the server. so there is no way to create the session after the page has loaded.
因此,如果您不想使用ajax,则只有一个/2解决方案.
so you have only one/2 solution if you don't want to use ajax.
解决方案1
sess.php
<?php
session_start();
$_SESSION['time']=$_GET['time'];
?>
js
head.appendChild(document.createElement('script')).src='sess.php?time='+offset;
note:head在这种情况下只是一个参考.
note:head is only a reference in this case.
但是
这也是异步的.
再说一次.页面加载后无法设置会话.
so again. there is no way to set the session after the page has loaded.
解决方案2
使用gd预加载php输出的图像,该图像也会设置您的会话.;)
如果您想知道我如何看待它(这将导致自然的页面加载,并且也将在ie6上正常工作)我只是不记得确切地在身体做完之前如何预加载图像了
if you want to know how i can look into it.(this would cause a natural page load & would prolly work also on ie6 )i just don't remember exactly how to preload images before the body does.
前段时间我遇到了同样的问题...我使用ajax.
I had the same problem some time ago ... i use 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);
另一方面...现在大多数现代浏览器都支持本地存储.
at the other side ... now most modern browsers support localstorage.
所有电话和现代的浏览器.
all phones & the modern browsers.
如果我存储这样的东西.为什么要使用php会话?
if i store things like that. why use a php session?
进行本地存储来代替它.
localstorage is made to replace that.
window.localStorage['offset']=((new Date().getTimezoneOffset()) * -1) * 60;
这篇关于在php会话变量中设置javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!