Javascript的加载/卸载,以让PHP $ _SESSION变量 [英] Javascript load/unload to get PHP $_SESSION variables

查看:116
本文介绍了Javascript的加载/卸载,以让PHP $ _SESSION变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个名为在页面加载的JavaScript函数和卸载,这将设置和取消会话变量。目前的JavaScript(与PHP线)看起来是这样的(使用jQuery的)

I'd like to have a javascript function called on page load and unload which will set and unset a session variable. Currently the javascript (in line with PHP) looks like this (uses jQuery)

window.onbeforeunload = function() {
   $.post('Example.php?y=".$id."&dir=0');
} 

$(document).ready(function() {
   $.post('Example.php?y=".$id."&dir=1');
}); 

这些都包含在PHP脚本,其中$ id是传递给页面变量。使用example.php是一个用ajax其中只是增加变量$ id来作为一个$ _SESSION变量存储阵列调用的脚本,如果DIR = 1,和从阵列如果DIR = 0移除变量。

These are included in a php script where $id is a variable passed to the page. Example.php is a script called using ajax which simply adds the variable $id to an array stored as a $_SESSION variable, if dir=1, and removes the variable from the array if dir=0.

问题是,这只是有时候按预期工作。当我加载网页,会话数组总是正确更新。当我卸载的页面,它有时工作,有时没有。我的猜测是,由于这是异步函数,变量正在被.ready函数调用设置后,页面卸载。但矛盾依然存在,即使我让网页坐一会儿,然后卸载它。有什么我做错了卸载功能?

The issue is that this just SOMETIMES works as expected. When I load the page, the session array is always updated properly. When I unload the page, it sometimes works and sometimes doesn't. My guess is that since these are async functions, the variable is being set by the .ready function call, AFTER a page unload. But the inconsistency persists even if I let the page sit for a while, then unload it. Is there something I'm doing wrong in the unload function?

  • 尝试设置阿贾克斯:假的在岗通话

  • Tried setting ajax:false in the post call

使用 $(窗口).unload() jQuery的构建,这只是没有工作试过。

Tried using the $(window).unload() jQuery construct, which just didn't work.

使用谷歌浏览器

推荐答案

$职位是异步的。这意味着,当该函数返回,请求可能仍然不已

$.post is asynchronous; this means that when the function returns, the request may still not have been made.

试着提出要求同步:

$.ajax('Example.php..', {
    async: false,
    type: 'POST'
});

请参阅 jQuery.ajax 文档。

See jQuery.ajax documentation.

这篇关于Javascript的加载/卸载,以让PHP $ _SESSION变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆