目前项目需要用到,实现原理很简单,提交一个ajax请求,并分别记录发送时间和收到回复时间即可。
代码转自:http://www.ttlsa.com/dev/use-js-ping-url-ping-ip/
$.ping = function(option) { var ping, requestTime, responseTime ; var getUrl = function(url){ //保证url带http:// var strReg="^((https|http)?://){1}" var re=new RegExp(strReg); return re.test(url)?url:"http://"+url; } $.ajax({ url: getUrl(option.url)+'/'+ (new Date()).getTime() + '.html', //设置一个空的ajax请求 type: 'GET', dataType: 'html', timeout: 10000, beforeSend : function() { if(option.beforePing) option.beforePing(); requestTime = new Date().getTime(); }, complete : function() { responseTime = new Date().getTime(); ping = Math.abs(requestTime - responseTime); if(option.afterPing) option.afterPing(ping); } }); if(option.interval && option.interval > 0) { var interval = option.interval * 1000; setTimeout(function(){$.ping(option)}, interval); // option.interval = 0; // 阻止多重循环 // setInterval(function(){$.ping(option)}, interval); } };
# 调用实例<div id="msg"></div> <script language="javascript" src="jquery.js"></script> <script language="javascript" src="ping.js"></script> <script> $.ping({ url : 'http://www.baidu.com', beforePing : function(){$('#msg').html('')}, afterPing : function(ping){$('#msg').html(ping)}, interval : 1 }); </script>
来源:https://www.cnblogs.com/tiduswj/p/4601768.html