Javascript Is It Possible To Check Whether File Is Exist Or Not Before Http Request?
I use the simple AJAX and use google debug then find that the url is not exist... The code is very simple: var http; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome
Solution 1:
Try this function
function urlExists(testUrl) {
var http = jQuery.ajax({
type:"HEAD", //Not get
url: testUrl,
async: false
})
return http.status!=404;
}
//Usage
if(!urlExists('http://www.mysite.com/somefileOrImage.ext')) {
alert('File not found');
}
HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
Read about head here
Solution 2:
you can use this function
function UrlExists(url)
{
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
var http=new XMLHttpRequest();
}
else {
var http=new ActiveXObject("Microsoft.XMLHTTP");
}
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Post a Comment for "Javascript Is It Possible To Check Whether File Is Exist Or Not Before Http Request?"