How can I check whether another server is up in javascript?
In my webapp I need to check if another server (on a different ip address) is up. I know I can't use direct ajax requests for this because of cross domain restrictions. I cannot use JSONP because I don't have any control over the other server. I also need to repeatedly check for the server being up as it may be unavailable some of the time. All these don't make it easy.
However since I only care about a request to the remote server succeeding (and I don't care about any data that the server might return), I was hoping that it would be possible.
I can't do this on the server side because the server side may or may not have visibility to the other server, what I really care about is that the client (web browser) have visibility.
I can append a new iframe to the page with the src equal to the remote server address but then how can I check when (IF) an iframe contents have been loaded successfully? Also how do I make periodic requests? By creating new iframes repeatedly? That seems quite unclean.
开发者_StackOverflow中文版Is there any way to do this cleanly and reliably?
function testServer(server, cb) {
var img = new Image();
img.onload = function() {
cb.call(this, img);
};
img.src = server;
}
var url = "http://placekitten.com/200/300/"
testServer(url, function _self(img) {
if (img.naturalHeight === 200) {
alert("win");
} else {
setInterval(function() {
testServer(url, _self);
}, 10000);
}
});
You want to load an Image from a remote server then check that the image height or whatever is what you expect it is.
If you can't place an image on the remote server then you will need to use CORS
A similar solution to Raynos' using jQuery:
$('<img src="http://domain.tld/path/to/a.png">').load(function(){
console.log("domain.tld is up.");
});
I know I can't use ajax for this because of cross domain restrictions.
Not true. See JSONP
精彩评论