开发者

check for file existence on the web using url passed

Friends:

I found these 2 pieces of code to test for file existence over the web. The JQuery version is very popular all over and the second one is simple javascript. I just grabbed a file from yahoo.com -- http://l.yimg.com/cv/mntl/tra/11q2/img_48880236.jpg

and made a small .html file using the code below. But i always get SUCCESS(or rather EXISTS) in my message, even after i modified the .jpg file mentioned above. I tried my .html file in IE* and Google chrome. Had linked the following jQuery file - jquery-1.4.2.min.js. Any help or suggestions would be welcome.

JQuery version -

$.ajax({
    url:'http://l.yimg.com/cv/mntl/tra/11q2/img_48880236--.jpg',
    type:'HEAD',
    error:
        function(){
            alert('DOES NOT EXISTS');
        },
    success:
        function(){
            ale开发者_Go百科rt('EXISTS');
        }
});

Javascript version -

var _url="http://l.yimg.com/cv/mntl/tra/11q2/img_48880236--.jpg" ;
var http = new XMLHttpRequest();
http.open('HEAD', _url, false);
http.send();
http.status !=404 ? alert('EXISTS') : alert('DOES NOT EXIST') ;


you can't use ajax calls to get assets from other domains. you get a sandbox exception.


only for image:

$('<img />')
    .bind('error', function(event) { alert('error 1'); })
    .bind('load', function(event) { alert('load 1'); })
    .attr('src', 'http://l.yimg.com/cv/mntl/tra/11q2/img_48880236.jpg');


$('<img />')
    .bind('error', function(event) { alert('error 2'); })
    .bind('load', function(event) { alert('load 2'); })
    .attr('src', 'http://l.yimg.com/cv/mntl/tra/11q2/img_48880236__.jpg');

example


When testing the jQuery version, it works. The JS-version is simply wrong.

It is a very incorrect usage of XMLHttpRequest. What should work is

http.onreadystatechange = function() {
    if(http.readyState == 4) {
        if(http.status == 200) {
            alert("EXISTS");
        } else { // this else is tricky if the server answers e.g. with a redirection.
                 // it will work in most of the cases.
            alert("DOES NOT EXISTS");
        }
    }
}

But this will only work as you stay on the same domain, because else you conflict with the same-origin policy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜