Javascript 如何使用src复制img标记,如果没有HTTP请求,就不应该缓存这些标记?

Javascript 如何使用src复制img标记,如果没有HTTP请求,就不应该缓存这些标记?,javascript,image,browser-cache,Javascript,Image,Browser Cache,因此,我的页面上有一个标签 当页面开始获取图像数据时,尝试ajax调用,并将其分配给要“复制”该数据的图像的“src” (function(){ var HANDLERS = {}; /** * I want to keep around a cached "Image" then the "callback" will be called with a * duplicate somehow - whatever comes back from here can be i

因此,我的页面上有一个
标签


当页面开始获取图像数据时,尝试ajax调用,并将其分配给要“复制”该数据的图像的“src”

(function(){
  var HANDLERS = {};

  /**
   * I want to keep around a cached "Image" then the "callback" will be called with a
   * duplicate somehow - whatever comes back from here can be inserted somewhere, but
   * hopefully no additional HTTP requests needs to be made!!
   * @param {Image} img
   * @return {Image} A copy of the incoming img
   */
  function duplicateImage(img) {
    // Does not work!! D'oh, is this even possible to achieve??
    return img.cloneNode(true);
  }

  /**
   * Users can call this to load the image. The callback is called when the image is ready.
   * In case the image fails the callback will be given an object that contains a success flag.
   * 
   * Example:
   * loadImage('/imageServlet?xxxx', function(result) {
   *   if (result.success) { $(body).append(result.image); }
   *   else { console.log("The image failed to load!") }
   * });
   * 
   * @param {string} src The src for the image
   * @param {function({success:boolean, image:Image})} callback Give a callback to be called when ready
   */
  window.loadImage = function(src, callback) {
    if (!HANDLERS[src]) {
      var queue = [];

      // This loadImage can be called more than once with the same src
      // before the image has successfully loaded. We will queue up any
      // callbacks and call them later, then replace this with function
      // that will directly invoke the callback later.
      HANDLERS[src] = function(callback) {
        queue.push(callback);
      }

      // Create the image here, but do it only once!!
      var el = new Image();

      // When the image loads, we will keep it around in the el
      // variable, but the callback will be called with a copy
      el.onload = function() {
        el.onload = el.onerror = null;
        var call = HANDLERS[src] = function(callback) {
          callback({
            success: true,
            image: duplicateImage(el) // This is where the image is duplicated!
          });
        }
        for (var i=0; i<queue.length; i++) {
          call(queue[i]);
        }
      }

      // This is just in case the image fails to load. Call any
      // queued callbacks with the success false.
      el.onerror = function() {
        el.onload = el.onerror = null;
        var call = HANDLERS[src] = function(callback) {
          callback({success: false});
        }
        for (var i=0; i<queue.length; i++) {
          call(queue[i]);
        }
      }
      el.src = src;
    }
    HANDLERS[src](callback);
  }
})();
由于这会将acutal映像写入“src”字段,而不是链接,因此您可以稍后将此映像从一个控件复制到另一个控件,而无需向服务器发出更多请求,非常简单:

$.ajax({
    type: "GET",
    url: 'some url',
    datatype:"image/jpg",
        success: function (data) {
            $('#img1').attr('src', url.createObjectURL(data));
            $('#img2').attr('src', url.createObjectURL(data));
        }
});
非jQuery版本

$('#img3').attr('src', $('#img2').attr('src'));

您可能希望将文件名(“src”)存储在一个数组中,以便javascript可以确定是否加载了图像。您可以使用画布渲染图像…将图像加载到画布后,您可以使用toDataURL()克隆此图像…无需从服务器获取。

我将尝试此操作;但是,假设它确实可以工作,那么只有当图像的src使用与我当前使用的页面相同的域时,它才会工作。在我的例子中,虽然它是同一个域,但它不是任何src的通用解决方案。我试图设置图像的
src
属性,比如
$('#img1').attr('src',data)
,但它不起作用。啊,真遗憾。你试过另一个吗<代码>文档.getElementById('img1').setAttribute?另外,请确保jQuery确实正确地选择了您的图像-如果它什么都没有,它将自动失败,我认为jQuery确实允许跨域请求。Canvas可能适用于FF/Chrome/Safari,但不适用于IE。超过90%的用户使用IE。哦,对不起……使用php。您可以将图像转换为base64…并将其存储在客户端浏览器的数组中。要渲染图像,只需使用。您知道如何在javascript中创建“somebase64string”吗?假设我有一些来自ajax调用的响应数据?我试过:-但它不起作用。它是一系列可以渲染为图像的字符串。它很好…太长了,无法包含。这就是..在PHP中:$base64变量现在将保存base64数据的方式。您可以使用ajax来获取base64已加密的图像:-)祝您好运
$('#img3').attr('src', $('#img2').attr('src'));
function myAjax() {
    var xmlHttp = new XMLHttpRequest();
    var url="some url";
    xmlHttp.open("GET", url, true);
    xmlHttp.setRequestHeader("Content-type", "image/jpg");
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById('img1').setAttribute('src', xmlHttp.responseBinary);
        }
    }
    xmlHttp.send();
}