Check whether a web resource exist or not

You can use HEAD requests to check whether a Web resource exists, and use up a lot less bandwidth doing so. The example code, exists.html, shows how this works by checking whether or not the data.txt file exists. The following example works by doing a HEAD request on that file, and checking the return Http status code — 200 means everything’s fine and the file is there, ready for use, but 404 means nope, file isn't there.


<script language = “javascript”>
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHttp”);
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open(“HEAD”, dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4) {
if (XMLHttpRequestObject.status == 200) {
obj.innerHTML = “URL exists”;
}
else if (XMLHttpRequestObject.status == 404) {
obj.innerHTML = “URL does not exist”;
}
}
}
XMLHttpRequestObject.send(null);
}
}
</script>

No comments:

Post a Comment

Flipkart