javascript – 使用jQuery异步加载图像

我想使用jQuery异步加载我的页面上的外部图像,我尝试了以下内容

$.ajax({ 
   url: "http://somedomain.com/image.jpg", 
   timeout:5000,
   success: function() {

   },
   error: function(r,x) {

   }
});

但它总是返回错误,甚至可以像这样加载图像?

我尝试使用.load方法并且它可以工作但我不知道如果图像不可用我怎么能设置超时(404).我怎样才能做到这一点?

解决方法:

不需要ajax.您可以创建一个新的图像元素,设置其源属性,并在完成加载后将其放置在文档中的某个位置:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...