我正在开发一个网络工具。它是用 PHP、HTML 和 MySQL 构建的。我的需要是每隔一段时间检查一次服务器的可达性。到目前为止,我已经尝试通过 JQuery-Ajax 函数发送一个简单的查询,如果收到查询,则显示 OK 消息,否则显示 ERROR 消息。此请求每 x 秒发送一次。我想知道是否有比我更好的方法或任何其他方法来确定服务器的可达性。我希望客户端知道服务器何时因某种原因不再事件。
这是我到目前为止所拥有的:
Client Side
<!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上提供的解决方案不适合我
最佳答案
使用图像可能会更有效(假设您的服务器成功发送图像表明它已启动):
function checkStatus(imgUrl) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.src = imgUrl;
img.onload = resolve;
img.onerror = reject;
});
}
var imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=d689de80c4e2';
var UPTIME_INTERVAL = 3000;
setInterval(function() {
checkStatus(imageUrl)
.then(function(success) { console.log('success') })
.catch(function(err) { console.log('error') })
}, UPTIME_INTERVAL);
编辑:在这种情况下,非常小的图像是理想的
关于javascript - 检查服务器的可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42792006/