使用AJAX将客户端运行时间记录到服务器日志文件中

Logging client run times to server log file using AJAX

本文关键字:服务器 日志 文件 记录 AJAX 客户端 运行时间 使用      更新时间:2023-09-26

因此,我必须将客户端脚本运行时间记录到服务器端日志文件中。我测量函数所花费的时间,然后通过ajax将其报告给服务器。这个代码看起来正确吗?我现在无法访问生产服务器,XAMPP出现故障,在我确定它能工作之前,我不想向老板展示这一点。这是我第一次使用AJAX,也是我第二次使用JS。

在我的index.php:中

function search(x,acc)
    {
           var startTime = new Date().getTime();
           //do work
           //
           var endTime = new Date().getTime() - startTime;
           var outputMessage = "The process took: " + max/1000 + "seconds";
           console.log(outputMessage);
           $.ajax({
           type: "POST",
           url: "ajaxCallback.php",
           data: {outputMessage},
           success: function()
                    {
                        console.log("Client Side : Ajax post     submitted.");
                    }
            }
    }

然后ajaxCallback.php:

<?php
    $stringData = $_POST['outputMessage']; 
    echo $stringData;
    $myFile = "logFile.log";
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, $stringData);
    fclose($fh);
?>

ajax调用中的data参数需要使用key/value对:

data: {outputMessage:outputMessage}

outputMessage中,未定义变量max

使用fopen:时,还应考虑正确的错误处理

if($fh = fopen($myFile, 'a')){
    fwrite($fh, $stringData);
    fclose($fh);    
}else{
    die("can't open file");
}

其他一切看起来都很直接。