Given 3 image url below
http://www.vbarter.com/images/content/3/2/32822.JPG (loads) http://www.vbarter.com/images/content/3/2/32784.png (loads)
http://www.bikewalls.com/pictures/abc.jpg (does not load)
I need a javascript/jquery function/code to automatically change the extension that works. Taking the case of above example will be very helpful. Here is my code snippet:
function imgError(image) {
image.onerror = "";
var image_src=image.src.substring(0, image.src.length-3);
image.src = image_src+"png";
$.ajax({
type: "HEAD",
url: image.src, //or your url
success: function(data){
},
error: function(data){
image.src = image_src+"JPG";
$.ajax({
type: "HEAD",
url: image.src, //or your url
success: function(data){
},
error: function(data){
alert("image fails");
},
});
},
});
return true;
}
HTML part
<img src="above url" onerror="imgError(this);">
Consider the situation where image src is vbarter.com/images/content/3/2/32822.jpg . Inside the inner ajax function, it enters into the error section and alerts "image fails". But vbarter.com/images/content/3/2/32822.JPG exists.
In fact your code is correct, but problem is due to the cross domain request issue using the ajax on jsfiddle site
I have modified your jsfiddle example, change the image source to an image that is under the same domain. You will find that the result is same as what you expected.
<div style="background-color:black;">
<img src="http://fiddle.jshell.net/img/logo.jpg" onerror="imgError(this);" />
</div>
<script>
function imgError(image) {
image.onerror = "";
var image_src=image.src.substring(0, image.src.length-3);
image.src = image_src+"jpg";
$.ajax({
type: "HEAD",
url: image.src, //or your url
success: function(data){
alert("png sucess");
},
error: function(data){
image.src = image_src+"png";
.ajax({
type: "HEAD",
url: image.src, //or your url
success: function(data){
alert("JPG success");
},
error: function(data){
alert("JPG fails");
},
});
}
});
return true;
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.