我基本上遵循这个问题的被接受的答案(Is it possible to ping a server from Javascript?)
更新
如果域名长度为15个字符(实际上是http:// + 15),它似乎按预期工作,但16个或更多字符会导致其崩溃。下面有更多细节。
我的问题在于,如果您使用的是看起来像有效域的东西,例如http://thisisdefinitelynotarealdomainname.com
,它会返回错误,但是代码认为错误是可以接受的(因为大多数应该是)。查看错误事件时,我不确定是否能够获取HTTP响应代码(即,如果是404,则将其视为无效)。
这里有一个jsFiddle显示了这个问题--它们都显示“responded”。如果您查看控制台,则无效域将返回404错误,并且两个有效域(如果在chrome控制台中,则不确定其他域)显示它们被解释为图像但作为文本/html传输--有任何方法读取404错误或mime类型吗?
var pinger = function () {
var ping = function (ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('responded');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e);
}
console.log(e);
};
this.start = new Date().getTime();
this.img.src = "http://" + ip + "/?now=" + this.start; // add the current time to work around caching
this.time = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
return {
ping: ping
};
}();
(function () {
var output = document.getElementById('output');
var servers = [
'localhost',
'google.com',
'okthisreallydoesntmakeanysense',
'okthisreallydoe',
'thisisashortone',
'thisisabitlonger'
];
servers.forEach(function (server) {
new pinger.ping(server, function (status, e) {
output.innerHTML += server + ': ' + status + '<br />';
});
});
})();
更新
更奇怪的是,在15个字符之前它似乎都正常。我已经更新了jsFiddle。请参见下面的响应符合预期的示例和不符合预期的示例。可能是什么原因呢?
'localhost',
'google.com',
'okthisreallydoesntmakeanysense', // doesn't work
'okthisreallydoe', // works (15 characters)
'thisisashortone', // works (15 characters)
'thisisabitlonger' // doesn't work (16 characters)
responded(Event e)
。在我看来,这个脚本有点不可靠。 - Daniel W.function(status, e) [..]
,并且它被用作callback('responded', e)
。 - Tom