【发布时间】:2017-03-14 16:53:57
【问题描述】:
我正在开发一个网络工具。它是用 PHP、HTML 和 MySQL 构建的。我需要每隔一段时间检查一次服务器的可达性。到目前为止,我已经尝试通过 JQuery-Ajax 函数发送一个简单的查询,如果收到查询,则显示 OK 消息,否则显示 ERROR 消息。此请求每 x 秒发送一次。我想知道是否有比我更好的方法或任何其他方法来确定服务器的可达性。我希望客户端知道服务器何时因任何原因不再活动。
这是我目前所拥有的:
客户端
<!DOCTYPE html>
<head>
<script src="assets/js/jquery.js"></script>
<link href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" rel="stylesheet">
</head>
<title>Check for MySQL availability</title>
<body onload="checking()">
<p style="display: inline;">MySQL</p>
<!-- Simple circle colored as orange (determining), red (unavailable) and green (available) -->
<p style="display: inline;" id="world"><i class="fa fa-circle" aria-hidden="true"></i></p>
</body>
<script>
function checking(){
var dataString = 'signum=some_string';
$.ajax({
type: "POST",
url: "testsql.php",
data: dataString,
cache: true,
timeout: 30000, //Timeout after 30 seconds
beforeSend: function(){
//Checking status... (orange)
$("#world").html('<i class="fa fa-spinner fa-pulse fa-fw"></i>').css('color', 'orange');
},
error: function() {
//Show MySQL as unavailable (red)
$("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
},
success: function(data){
if(!data){
console.err("Error!");
//MySQL is unavailable (red)
$("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
}else if(data){
//MySQL is available (green)
console.log("MySQL available!");
$("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'green');
}else{
//MySQL is unavailable (red)
console.err("Error!");
$("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
}
}
});
//Send Ajax requests every 3 seconds
var t = setTimeout(checking, 3000);
}
</script>
</html>
注意:Is there any way to check reachability test of server in jQuery 上提供的解决方案对我不起作用
【问题讨论】:
-
我猜代码看起来不错。您可以通过检查 http 状态代码来扩展它以更具体,这样您就可以查看问题是互联网连接还是数据库本身等。如果您可以使用
websockets或其他server push technology,您没有做这一切,只是让服务器通知客户端。但否则你会被这种polling卡住。 -
尝试通过在错误函数上捕获错误 jqXHR、textStatus、errorThrown 来进行扩展,但我想我知道有一个错误足以让我的客户意识到这一点。不过,我将进一步研究 websockets 的实现。感谢您的洞察力。
标签: javascript jquery html mysql ajax