我想使用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);
}
});