问题描述
我正在尝试使用此处调用的解决方案:如何在不重新加载页面的情况下使会话保持活动状态?
I am trying to use the solution called in here:How to keep session alive without reloading page?
不幸的是,我无法使用它,我在Javascript和jQuery方面的经验非常有限.
Unfortunately I can't get it to work, I have very limited experience with Javascript and jQuery.
这是我的index.php
This is my index.php
<?php
session_start();
echo session_id();
$_SESSION['id'] = session_id(); //just so there is a variable within the session
?>
编辑:在评论/答案后添加了jquery库
added jquery library after comment/answer
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
setInterval(function(){
$.post('refresh_session.php');
}, 60000);
</script>
这是我写入文件的refresh_session.php,因此我可以测试该文件是否真正被调用.
And this is the refresh_session.php where I write to a file, so I can test if the file is actually being called.
<?php
session_start();
if (isset($_SESSION['id'])){
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
}
$date = new DateTime();
$fp = fopen('data.txt', 'a');
fwrite($fp, $date->format('Y-m-d H:i:s') . " " . session_id() ."\n");
fclose($fp);
?>
如果我手动调用refresh_session.php,我会在data.txt中看到日期.如果我打开index.php并等待data.txt文件更改,则不会发生任何事情.
If I call refresh_session.php manually, I see the date showing up in data.txt.If I open up index.php and wait for the data.txt file to change, nothing happens.
我在这里想念什么?
推荐答案
我不知道为什么,但是在复制粘贴了您的javascript代码后–代码片段中出现了奇怪的字符.可能是字符集问题.代码看起来不错,但是方括号仅看起来像方括号.这不是括号.这是什么?我不知道,但是请看一下粘贴您的代码后,我在Code Snipped中得到了什么:
I don't know why, but after copy-paste your javascript code – I've got strange characters in Code Snipped. It can be charset problem. Code looks good, but bracket only looks like bracket. It's not bracket. What it is? I don't know, but look at that what I've got in Code Snipped after pasting your code:
如果使用良好的字符集编写代码,则将执行.取得该工作代码:
Code will execute if you write it using good charset. Take that working code:
setInterval(function(){
$.post('refresh_session.php');
alert("dsa");
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
顺便说一句-alert
当然只是测试,您可以删除它.
By the way – alert
is of course only test, you can delete this.
因此,答案是–检查您的字符集.
So, the answer is – check your charset.
这篇关于Javascript不调用文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!