如何每秒使用jquery/javascript更新PHP当前时间戳 [英] How to update the PHP current timestamp using jquery/javascript every second
问题描述
我正在使用PHP和jQuery/JavaScript处理PHP购物车计时器脚本.
I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
我每秒钟都要迭代一次set-interval函数,以获取PHP的当前时间戳.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
将第一个产品添加到购物车后,计时器开始运行,然后停止计时器,提示用户是否要继续还是取消.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
我的代码如下
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
仅存储第一个迭代值的currenttime变量没有得到更新.
The currenttime variable only storing the 1st iteration value is not getting updating.
如何解决此问题?
请帮助我解决问题.
先谢谢了.
推荐答案
您实际上并不是在setTimeout循环中向服务器请求时间.
You're not actually requesting a time from the server in your setTimeout loop.
此行
currenttime = "<?php echo date('h:i:s', time()); ?>";
在第一次生成页面且不再更改时设置.如果要更新时间,则需要向服务器发送请求.不过,这可能不是最好的方法.
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
这篇关于如何每秒使用jquery/javascript更新PHP当前时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!