Reputation: 33
i try load image. but every time to console log set "error".
Where my error? first way
$('#cont').click(function() {
$.ajax({
type: "GET",
url: "http://pp.vk.me/c608129/v608129926/13d7/M78M4KmekWI.jpg",
dataType: "image/gif",
success: function(img) {
i = new Image();
i.src = img;
$(this).appned(i);
},
error: function(error, txtStatus) {
console.log(txtStatus);
console.log('error');
}
});
});
Upvotes: 1
Views: 1043
Reputation: 2826
If you have a usecase that requires the bytes of the image to be transfered through the ajax call then take a look at this post: http://stick2basic.wordpress.com/2013/01/24/loading-image-dynamically/
In summary,
You might even be able to convert the bytes returned from the ajax call to base64 encoding on the client side as well. More info: (Javascript) Convert Byte[] to image
Upvotes: 0
Reputation: 816930
You cannot make Ajax requests to external sites, unless they explicitly allow it. That's called the same origin policy.
In your case, you don't even have to make an Ajax request. You should just assign the URL to the src
property of the image:
$('#cont').click(function() {
var i = new Image();
i.src = 'http://pp.vk.me/c608129/v608129926/13d7/M78M4KmekWI.jpg';
$(this).append(i);
});
or more jQuery-like:
$('#cont').click(function() {
$('<img />', {
src: 'http://pp.vk.me/c608129/v608129926/13d7/M78M4KmekWI.jpg'
}).appendTo(this);
});
The browser will load the image by itself.
You can bind an error event handler to the image and do whatever you want to do if image is not available, and a load event handler to get notified that the image was loaded:
$('#cont').click(function() {
$('<img />', {
src: 'http://pp.vk.me/c608129/v608129926/13d7/M78M4KmekWI.jpg',
on: {
load: function() {
console.log('Image loaded successfully');
},
error: function() {
console.log('Error while loading image');
}
}
}).appendTo(this)
});
Upvotes: 2