我有一些PHP代码,它说你注册的时间,并给出了它多久前的近似值。我一直在考虑尝试用javascript刷新它,但我正在努力找到我想要的确切内容,而且由于我对它的了解并不好,我现在有点坚持让它工作。
基本上,这是我目前拥有的代码,该函数是显示自唱歌以来的时间的东西
Date registered: <?PHP echo date('jS F Y', $_SESSION['User_Date'])." at ".date('G:i:s', $_SESSION['User_Date']);
echo " (".time_delta('now',date('F j Y G:i:s', $_SESSION['User_Date'])).")"; ?>
这将输出类似的东西:注册日期:2013年11月4日0:57:
31(约34分钟前)
我有这个用于javascript,但我不知道如何让它只是更新文本而不是重定向页面。
<script>
setInterval(function() {
window.location.href = "timeupdate.php";
}, 1000);
</script>
是否有一种简单的方法可以做到这一点,或者是否值得在 CPU 使用率方面避免它?
正如评论所暗示的那样,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 函数,您需要让服务器在脚本运行之前(即在呈现页面时)回显出 Session 变量,如下所示:.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
});
如果您在现有脚本之前将 jQuery 添加到您的页面<head></head>
标记中,这应该可以工作:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">