How can I use javascript to determine whether the requested url/link is valid (connectable and available )?
Introduction
There is an address book system deployed on several servers at the same time, but there is a Address Book link on the home page to link to this system. the problem is that sometimes the link points to a server with a failure, so you want to point to other servers when the server is faulty (the service is unavailable.
Solution 1: XMLHTTP
<Script language = "javascript">
Function getURL (url ){
Var xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");
Xmlhttp. open ("GET", url, false );
Xmlhttp. send ();
If (xmlhttp. readyState = 4 ){
If (xmlhttp. Status! = 200) alert ("nonexistent ");
Return xmlhttp. Status = 200;
}
Return false;
}
</Script>
<A href = "http://www.bkjia.com/aaa.asp" onclick = "return getURL (this. href)"> csdn </a>
Disadvantage: ActiveXObject is used, so it is IE Only. Non-IE kernel browsers are not available.
Solution 2: jQuery Extension
For the following content, refer to [1].
Home: http://plugins.jquery.com/project/linkchecker
Demo page: http://sidashin.ru/linkchecker/
A call example is provided in the downloaded package.
Supplement:
If jQuery is used for a specific URL, you do not need a plug-in as follows:
$. Ajax ({
Url: 'http: // some.url.com ',
Type: 'get ',
Complete: function (response ){
If (response. status = 200 ){
Alert ('payby ');
} Else {
Alert ('invalid ');
}
}
});