我使用远程API使用AJAX每2秒提取一次应用程序的控制台日志。这在所有情况下都可以正常工作,但用户单击页面上的链接以移动到其他位置除外。这样做会触发错误回调,而不会实际提供任何数据,但不会刷新页面。
任何人都可以告诉我是什么原因造成这种情况并找到问题的潜在解决方案吗?
<script>
var server_id = getUrlParameter('id');
var lastFetchTime = 1;
$(document).ready(function()
{
getConsoleMessages();
setInterval(function()
{
getConsoleMessages();
},2000);
});
function getConsoleMessages()
{
var consoleBox = document.getElementById("console");
$.ajax({
type: "POST",
url: "consoleHandler.php",
data: { 'action': 'getConsoleMessages', 'server_id': server_id, 'since': lastFetchTime },
dataType: 'json',
success: function(data)
{
console.log(data);
var messages = data['message']['chatdata'];
if (messages.length > 0)
{
messages.forEach( function (item)
{
// Skip lines we've already displayed
if (lastFetchTime >= item.timestamp)
{
return;
}
var timestamp = item.time; // /Date(1440823073243)/
var timestamp = timestamp.substring(timestamp.lastIndexOf("(")+1, timestamp.lastIndexOf(")"));
var contents = item.message;
lastFetchTime = item.timestamp;
// Get Date/Time in Milliseconds
var date = new Date(parseInt(timestamp));
var time = pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
console_log("<font color='blue'>[" + time + "]</font>" + " " + contents);
});
}
consoleBox.scrollTop = consoleBox.scrollHeight;
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
}
});
};
</script>
consoleHandler.php
$action = $_POST['action'];
$response = array();
switch ($action)
{
case "getConsoleMessages":
{
foreach ($_SESSION['servers'] as $server)
{
if ($server['whmcs_id'] == $_POST['server_id'])
{
$mcmyadmin = new McMyAdmin($server['mcma_user'], $server['mcma_pass'], $server['mcma_ip'], $server['mcma_port']);
$result = $mcmyadmin->getChat($_POST['since']);
$response['status'] = "success";
$response['message'] = $result;
}
}
echo json_encode($response);
break;
}
}