1

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');
    }
     });
    });
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

2

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)
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

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,

  1. backend server returning the image needs to send the base64 encoding of the bytes of the image.
  2. The ajax call sets the src of the img node to 'data:image/png;base64,' + bytes

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

Community
  • 1
  • 1
joseph
  • 2,429
  • 1
  • 22
  • 43