我有一个页面,我试图遍历mysql查询的结果,在此块中,我需要将JS new date().getTime()
值发送到php函数以计算经过的时间,所有这些都在while循环内。
我该如何实现?
我的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函数计算经过的时间。
最佳答案
嗯..奇怪...但是当然如果您认为这很重要...
如果您认为可以将js时间从客户端返回到您的位置,而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));
}