我得到一个javascript函数,使日期和时间自动更新。
下面是我从这个URL找到的脚本:http://jsfiddle.net/pLsgJ/1/setInterval(function() {
var currentTime = new Date ( );
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("timer").innerHTML = currentTimeString;
}, 1000);
然后显示结果,我们必须像这样用HTML调用id:
<div id="timer"></div>
但是我想把结果像这样传递给PHP:
$timer = $_GET['timer'];
但是它完全失败了。有可能将javascript元素id传递到php吗?我该怎么做呢?
请帮帮我
在表单
中创建隐藏字段<form id= "myform">
<input type="hidden" name="timer" id="timer" value="">
</form>
JS: -
$('#timer').val() = currentTimeString;
$('form#myform').submit(); // for submit after value set may be work not tested
并且在提交表单时,您将得到:-
$timer = $_GET['timer'];
Javascript变量是本地创建的。在你的电脑上。PHP变量是在服务器上创建的。
要将javascript值从本地客户端发送回服务器,您需要一个表单或ajax请求。
这是一个简单的jQuery Ajax请求:$.get( "example.php", { timervalue: mytimevalue } );
使用这个脚本,你可以发送你的本地"mytimevalue"到你的服务器。
在表单中发送它是一个选项,如前所述,或者通过使用ajax。但最简单的方法是用JS将其设置为cookie,然后用PHP读取cookie。
JS
document.cookie="timer=" + timer;
$timer = $_COOKIE["timer"];
在这里我将为您添加一行:
setInterval(function() {
var currentTime = new Date ( );
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("timer").innerHTML = currentTimeString;
document.cookie="timer=" + currentTimeString;
}, 1000);