我有一个javascript计数器。如果计数器= 0,则价格改变。我想知道javascript的价格变量php的值。但在php中价格一次就会上涨,仅此而已。
<?php global $p; $p = 1000; ?>
var pr = <?php echo $p;?>;
function downCounter(tim)
{
var t;
counter=tim-1;
var elem=document.getElementById('counter');
var price= document.getElementById('price');
var days = parseInt(counter / 86400),
hours = parseInt(counter / 3600) % 24,
minutes = parseInt(counter / 60) % 60,
seconds = counter % 60,
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
elem.innerHTML=(days ? days + dayname : '') + hours + ':' + minutes + ':' + seconds;
price.innerHTML=(pr);
if (counter==0)
{
downCounter('43200');
<?php $p += 500; ?> <-- works once
pr = <?php echo $p; ?>;
} else {
clearTimeout(t);
t=setTimeout("downCounter('+"+(tim-1)+"')", 1000);
}
return false;
}
downCounter('43200');
</script>感谢所有人,但是我如何保护我的pr变量不会在源代码中更改,然后通过ajax发送?
发布于 2014-06-06 23:04:35
这里的问题源于您对上下文的混淆: PHP在服务器上运行并输出HTML,HTML被发送到客户端;Javascript在客户端运行,不与服务器通信(除非您使用AJAX或其他方法)。
PHP在服务器上执行,并被发送到客户端,因此客户端得到如下内容:
var pr = 1000; // inserted with the PHP echo statement
function downCounter(tim)
{
var t;
counter=tim-1;
var elem=document.getElementById('counter');
var price= document.getElementById('price');
var days = parseInt(counter / 86400),
hours = parseInt(counter / 3600) % 24,
minutes = parseInt(counter / 60) % 60,
seconds = counter % 60,
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
elem.innerHTML=(days ? days + dayname : '') + hours + ':' + minutes + ':' + seconds;
price.innerHTML=(pr);
if (counter==0)
{
downCounter('43200');
pr = 1500; // $p += 500 on previous line of PHP code; echoed here
} else
{
clearTimeout(t);
t=setTimeout("downCounter('+"+(tim-1)+"')", 1000);
}
return false;
}
downCounter('43200');
</script>这就是在客户机上执行的东西--明白为什么它不能按您想要的方式工作了吗?Javascript使用静态值: 1000和1500。
如上所述,如果您希望将这些值返回到服务器,则需要编写一些Javascript代码来实际传回这些值。
https://stackoverflow.com/questions/24084910
复制相似问题