Javascript:检查服务器是否在线?

编程入门 行业动态 更新时间:2024-10-26 16:24:37
本文介绍了Javascript:检查服务器是否在线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

检查我的服务器是否通过JavaScript在线的最快方法是什么?

What's the fastest way to check if my server is online via JavaScript?

我尝试过以下AJAX:

I've tried the following AJAX:

function isonline() { var uri = 'MYURL' var xhr = new XMLHttpRequest(); xhr.open("GET",uri,false); xhr.send(null); if(xhr.status == 200) { //is online return xhr.responseText; } else { //is offline return null; } }

问题是,如果服务器是离线。如何设置超时,以便如果在一段时间后没有返回,我可以假设它处于脱机状态?

The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn't returning after a certain amount of time, I can assume it is offline?

推荐答案

XMLHttpRequest 不支持跨域工作。相反,我会加载一个小的< img> ,你希望它能够快速返回并观看 onload 事件:

XMLHttpRequest does not work cross-domain. Instead, I'd load a tiny <img> that you expect to come back quickly and watch the onload event:

function checkServerStatus() { setServerStatus("unknown"); var img = document.body.appendChild(document.createElement("img")); img.onload = function() { setServerStatus("online"); }; img.onerror = function() { setServerStatus("offline"); }; img.src = "myserver/ping.gif"; }

编辑:清理我的答案。可以在同一个域上使用 XMLHttpRequest 解决方案,但如果您只想测试服务器是否在线,则img加载解决方案最简单。没有必要混淆超时。如果你想使代码看起来就像是同步的,这里有一些对你的语法糖:

Cleaning up my answer. An XMLHttpRequest solution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest. There's no need to mess with timeouts. If you want to make the code look like it's synchronous, here's some syntactic sugar for you:

function ifServerOnline(ifOnline, ifOffline) { var img = document.body.appendChild(document.createElement("img")); img.onload = function() { ifOnline && ifOnline.constructor == Function && ifOnline(); }; img.onerror = function() { ifOffline && ifOffline.constructor == Function && ifOffline(); }; img.src = "myserver/ping.gif"; } ifServerOnline(function() { // server online code here }, function () { // server offline code here });

更多推荐

Javascript:检查服务器是否在线?

本文发布于:2023-11-23 10:37:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621132.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在线   服务器   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!