因此,我必须将客户端脚本运行时间记录到服务器端日志文件中。我测量函数所花费的时间,然后通过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");
}
其他一切看起来都很直接。