正如评论所暗示的那样,AJAX 是您的答案。
使用jQuery,ajax 调用看起来像这样:
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: "timeupdate.php",
type: "GET",
dataType: "html",
success: function(html) {
$("#date_registered_element").html(html);
}
});//end ajax call
},1000);//end setInterval
});//end docReady
这会将 timeupdate.php 返回的文本输出到 id 为“date_registered_element”的 div -> 将其更改为您希望输出更新文本的 div 的名称。
为了将会话变量传递给 Ajax 函数,您需要让服务器在脚本运行之前(即呈现页面时)回显会话变量,如下所示: HTML:
<div id="user_date" style="display: none;">
<?php echo $_SESSION["User_Date"]; ?>
</div>
请注意:您需要非常小心。在浏览器查看源代码或开发人员工具中查看您的标记的任何人都将能够看到回显的 SESSION 变量。只有当数据不存在安全风险时,您才应该这样做。在我看来,您最好在 Ajax 调用中不传递 GET 变量,而只在 timeupdate.php 脚本中引用 SESSION 变量。SESSION 变量的重点是为 HTTP 提供类似状态的功能,因此您永远不需要通过 HTTP 请求发送 SESSION 变量。
也就是说,如果您希望按照当前设置的方式进行操作,那么代码如下。
将 SESSION 变量回显到页面后,您可以使用 jQuery 从 id 中收集值并将其传递给 Ajax 函数:
Javascript/jQuery:
var url = "timeupdate.php?time=" + $("#user_date").text();
//pass the url to the Ajax function in the ajax function like this:
$.ajax({
url: url,
//the rest of your ajax function here
});
如果您在现有脚本之前<head></head>将 jQuery 添加到页面标签中,则应该可以:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">