我想使用 javascript
ping 几个站点,并找到了这支笔并执行了我想要的操作。
但是,我不明白当我将 goo12121212gle.com
添加到站点列表作为测试时,它会显示域已响应
,但在控制台日志我看到 ERR_NAME_NOT_RESOLVED
?
我是 JS 新手,但我不确定为什么下面的脚本既说该网站存在,又不同时说?脚本中是否缺少某些内容?
function ping(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('online');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('offline', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
var PingModel = function (servers) {
var self = this;
var myServers = [];
ko.utils.arrayForEach(servers, function (location) {
myServers.push({
name: location,
status: ko.observable('unchecked')
});
});
self.servers = ko.observableArray(myServers);
ko.utils.arrayForEach(self.servers(), function (s) {
s.status('checking');
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
});
};
var komodel = new PingModel(['goo12121212gle.com','msn.com','104.46.36.174','23.97.201.12']);
ko.applyBindings(komodel);
最佳答案
onerror- 和 onload-callback 都使用“responded”作为消息,因此无法区分它们:
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e); // <--- change this to a different message
}
};
或者,您可以只检查 e
参数是否已设置:
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
关于javascript - 使用 knockout.js Ping 网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792831/