将javascript元素id传递给php

时间:2014-08-13 07:03:07

标签: javascript php jquery html

我有一个javascript函数可以自动更新日期和时间。

以下是我在此网址中找到的脚本: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?我怎么能这样做?

请帮帮我

3 个答案:

答案 0 :(得分:2)

以表格

创建隐藏字段
<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'];

答案 1 :(得分:0)

Javascript变量在本地创建。所以在你的电脑上。 PHP变量在您的服务器上创建。

要将本地客户端的javascript值发送回服务器,您需要表单或ajax请求。

这是一个简单的jQuery Ajax请求:

$.get( "example.php", { timervalue: mytimevalue } ); 

使用此脚本,您可以发送您当地的&#34; mytimevalue&#34;到你的服务器。

答案 2 :(得分:0)

以表格形式发送,或者使用ajax。但最简单的方法是使用JS将其设置为cookie,然后使用PHP读取cookie。

JS

document.cookie="timer=" + timer;

PHP

$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);