js 检测远端网站是否可以访问

编程语言
0 296

js 检测远端网站是否可以访问
function ifUp(url,onUp,onDown) {
	// make random string
	var RANDOM_DIGITS = 7; // this is sufficient. Don't do more than ~12.
	var pow = Math.pow(10,RANDOM_DIGITS);
	var randStr = String(Math.floor(Math.random()*pow)+pow).substr(1);
	// create and load image
	var img = new Image();
	img.onload = onUp;
	img.onerror = onDown;
	img.src = url+"?"+randStr;
}
 
ifUp("http://host.kan.pub/favicon.ico",
	function(){
		// do something
		alert("Server is responding");
	},
	function(){
		// do something else
		alert("Server is *not* responding");
	}
);