具有淘汰表的Ping网站

问题描述 投票:1回答:1

我想使用javascript对几个站点执行ping操作,并找到了这支笔,可以完成我想要的操作。

但是,当我将goo12121212gle.com添加到站点列表作为测试时,我不明白,它显示该域具有responded,但在控制台日志中却看到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);

https://codepen.io/lyellick0506/pen/NGJgry

javascript knockout.js
1个回答
0
投票

onerror和onload回调均使用“已响应”作为消息,因此无法区分它们:

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.