AJAX的简单访问持续时间记录器
Simple visit duration logger with AJAX
我在记录访问持续时间时遇到问题。
我写了这样的测试html文件:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
alert("test");
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
method: 'get',
onComplete:handlerFunction
});
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
PHP文件(visitor_log/ajax_store_visit_duration.PHP):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
log($text);
}
else die("error");
function log($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
当我在浏览器中键入:
http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123
它按照我的意愿创建文本文件,但onbeforeunload
事件中的AJAX调用似乎不起作用。
我的代码出了什么问题
编辑:
我创建了测试函数来查找AJAX调用的问题。
function testajax(){
this.chrono = new Date().getMilliseconds() - this.chrono;
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
blockingRequest.send();
return null;
}
window.onload = testajax;
</script>
</body>
这也不起作用。
好的,所以有目的地不使用jQuery:
这是PHP:
<?php
function loggit($text) {
$myFile = "/tmp/test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
if(isset($_GET["visit_duration"])) {
$text = $_GET["visit_duration"];
loggit($text);
}
else die("error");
?>
这是HTML:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
您想要使用异步请求(请参阅发送到blockingrequest.open的false),但要注意这是一个BLOCKING请求(因此得名)。
此外,我还将php函数的名称从"log"更改为"loggit"log是php自然对数函数。。。
相关文章:
- 如何在模式弹出窗口中使用引导程序日期和时间选择器
- 两个日期时间选择器
- Angular Datetimepicker:指令'的模板;uib时间选择器'必须只有一个根元素
- 在jQuery中,短距离长持续时间的精细字体大小动画
- Javascript-如何使用bootstrap日期时间选择器自动计算两个时间输入之间的差异
- 时间选择器:如何通过更改第一个值来更改第二个值
- 创建一个倒计时计时器脚本,该脚本计算声音文件的持续时间,而不是特定的日期
- 如何禁用引导程序时间选择器中的按钮
- 如何检查日期选择器和时间选择器元素是否使用JQuery/Javascript设置
- 引导时间选择器在增加或减少小时和分钟的同时获取 NaN
- 使用引导时间选取器时,没有更新数据ng模型值
- 引导程序日期时间选择器来自另一个日期时间选择器
- 寻找使用Javascript从Kendo UI时间选择器中减去时间的更好替代方案
- 如何在 JavaScript 中设置计时器持续时间
- 在 VideoJS 中添加事件侦听器,用于在运行时获取视频持续时间
- AJAX的简单访问持续时间记录器
- 在计时器运行后,将持续时间添加到JS setTimeout
- 我想要一个引导时间选择器从下拉列表中选择开始时间,其中持续时间间隔为30分钟
- 音频持续时间返回NaN需要一些修改来运行播放器
- 在javascript中修改计时器间隔函数也给出总持续时间时遇到麻烦