我有一个页面,我正在尝试循环来自mysql查询的结果,在这个块中,我需要将JS new date().getTime()
值发送到php函数以计算已过去的时间,所有这些都在循环。
我如何实现这一目标?
我的php页面如下:
<body>
<?php
while($rows = $result->fetch_assoc()){
echo "<div>".// now here i want to send the time value from JS to function
like time($a JS value)."</div>"
}
?>
</body>
编辑也许我让人困惑,试图弄清楚执行时间并非如此。我希望将来自mysql查询的时间值与客户端机器在PHP函数中从JS的时间进行比较。我的php函数计算经过的时间。
答案 0 :(得分:1)
如果您认为可以将js-time从客户端返回到您的PHP脚本仍然运行任何代码,那么它将无法工作!
但如果你愿意,你可以通过ajax获取信息。
我们走了: 将sql查询中的时间值添加到呈现的网站的DOM对象中 通过直接添加javascript var最简单(只要您使用javascript读取正确的对象值,您也可以使用您选择的隐藏或甚至可见的DOM对象)
为了缓解问题(对我而言)我假设要实现jQuery。
javascript标题
var sqltime = 1360599506; // unix timestamp set by php
// now let's get the information from the user incl his timezone
var tnow = new Date(); // string something like: "Mon Feb 11 2013 17:24:06 GMT+0100"
// and a timestamp-like number for tnow
var tstmp = var now = Math.round(tnow.getTime() / 1000)
//and now send those three values via ajax to the server:
var postdata = {action: 'ajaxtime', ts: sqltime, tj: tstmp, tr: tnow};
$.ajax({
type: 'POST',
url: "http://example.com/my.php",
data: postdata,
success: function (response)
{
//do something with the response if you want. just decode the received json string if any
}
});
//you could also compare the two timestamps on clientside if this is more convenient.
并且php应该有一个触发器将ajax请求尽可能地放入你的php中(但在任何事情得到回应或查询到你的sql之前!!)
if (array_key_exists('ajaxtime', $_REQUEST))
{
$sql time = $_POST['ts'];
$js_timestamp = $_POST['tj'];
$readable_js_time = $_POST['tr'];
// here you can calculate the timestamps and get timezone from the readable_js_time and do whatever you need to.
$json['success'] = true;
$json['result'] = "my result from the calculation";
// make sure no other code of this php is executed because of the ajaxtime request
die();
//if you want to response with a json string to parse in the javascript response use this:
//die (jsonEncode($json));
}
答案 1 :(得分:0)
你应该更好地使用PHP的时间函数:
$currTime = time();
但是,如果客户端浏览器和您的Web服务器可能位于不同的时区,那么您可以使用get query参数将javascript时间传递给PHP脚本,然后在PHP脚本中访问它,如:
$currTime = $_GET['jsCurrTime'];
答案 2 :(得分:0)
如果要在PHP中测量执行时间,则需要使用microtime
;
$start = microtime(true);
// Some code to measure
$time = microtime(true) - $start;