Trouble on retrieving 'favicon.ico' images using AJAX HTTP requests

心不动则不痛 提交于 2019-12-04 20:24:18

You can't do XmlHttpRequests on URLs that are not on the same domain/port/protocol than the current page.

You can, however, check that an image exists by using an Image object and the onload and onerror events:

var img = new Image;
var src = 'http://www.facebook.com/favicon.ico';
img.onload = function() {
    // the image exists, display it
};
img.src = src;

You can wrap this in a function:

function imageExists(src, callback) {
    var img = new Image;
    img.onload = function() {
        callback(src, true);
    };
    img.onerror = function() {
        callback(src, false);
    };
    img.src=src;
}

And use it like this:

imageExists('http://www.facebook.com/favicon.ico', function(src, exists) {
    if (exists) {
        $('body').append('<p>The image loaded correctly!</p>');
        $('<img>').attr('src', src).appendTo('body');
    } else {
        $('body').append('<p>oops, error</p>');
    }
});

Test it here: http://jsfiddle.net/YpBsJ/2/

Same-origin-policy prohibits the cross domain requests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!