开发者

both success and error callbacks used at all times

I have a simple code checking if image url is valid. Unfortunately whether image is found or not I'm getting both error and success callbacks.

var url = obj.image;
开发者_运维百科$.ajax({
    url: url,
    async:false,
    success: function(data){
        console.log('success');
    },
    error:function (xhr, ajaxOptions, thrownError){
        console.log('error');
    }                             
});

Image: http://images.virtualdesign.pl/images/21422jqerrors.png

I'm using jquery 1.4.3 together with jquery mobile 1.0a3.


I'd rather suggest not to use an Ajax request for this purpose. I'd go with

function checkImage(url, succ, err) {
    var checkImg = new Image();
    checkImg.src = url;
    checkImg.onerror = function() {
        console.log('error');
        err();
    };
    checkImg.onload = function() {
        if(!this.width || !this.height) {
           console.log('error'); 
           err();
        }
        else {
            console.log('success');
            succ();
        }
    };
}

Using it like:

checkImage('http://mydomain/images/foo.jpg', function() {
    alert('yay');
}, function() {
    alert('oops');
});

Demo: http://jsfiddle.net/9RxrA/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜