简体   繁体   English

我想从远程站点将图像加载到div,请使用ajax + jquery

[英]i want load image to div from remote site, use ajax+jquery

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');
    }
     });
    });

You cannot make Ajax requests to external sites, unless they explicitly allow it. 您不能向外部站点发出Ajax请求,除非它们明确允许。 That's called the same origin policy . 这就是所谓的原产地政策

In your case, you don't even have to make an Ajax request. 就您而言,您甚至不必发出Ajax请求。 You should just assign the URL to the src property of the image: 您应该将URL分配给图像的src属性:

$('#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: 或更像jQuery的:

$('#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)
});

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/ 如果您有一个用例需要通过ajax调用传输图像的字节,请看一下这篇文章: 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. 返回图像的后端服务器需要发送图像字节的base64编码。
  2. The ajax call sets the src of the img node to 'data:image/png;base64,' + bytes Ajax调用将img节点的src设置为'data:image / png; base64'+字节

You might even be able to convert the bytes returned from the ajax call to base64 encoding on the client side as well. 您甚至还可以在客户端将ajax调用返回的字节转换为base64编码。 More info: (Javascript) Convert Byte[] to image 更多信息: (JavaScript)将Byte []转换为图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM