Javascript 通过 jQuery Ajax 加载图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33704678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:22:11  来源:igfitidea点击:

Load an image through jQuery Ajax

javascriptphpjqueryajaximage

提问by Emanuel Elliott

I am creating an application which browses a large amount of pictures. At this point, that portion of the project is done and it sorts, filters, and loads the correct pictures, and even splits them into separate pages for faster loading.

我正在创建一个浏览大量图片的应用程序。此时,项目的那部分就完成了,它对正确的图片进行排序、过滤和加载,甚至将它们拆分为单独的页面以加快加载速度。

This works great, but it still takes over 8 seconds to load the 25 pictures per page. I have done some research and I have concluded that using asynchronous jQuery Ajax requests would be the best to load them all at the same time as fast as possible.

这很好用,但每页加载 25 张图片仍然需要 8 秒以上。我做了一些研究,我得出的结论是,使用异步 jQuery Ajax 请求最好尽可能快地同时加载它们。

Here is my code for this so far:

到目前为止,这是我的代码:

var imageArray = <?php if (!empty($images)) {echo '["' . implode('", "', $images) . '"]';} else {echo "false";} ?>;
console.log(imageArray);
console.log(imageArray.length);
for (i = 0; i < imageArray.length; i++) {
    $.ajax({
        type: 'GET',
        url: imageArray[i],
        dataType: 'image/jpg',
        async: true,
        success: function (data) {
            $("#" + i).attr("src", data);
        }
    });
}

The problem with this code is that it doesn't load nothing but an empty white square with a grey border. When I modify the code and run it in console in Chrome, dataends up being a string of jumbled up characters which I presume are the raw image data.

这段代码的问题在于它除了一个带灰色边框的空白色方块之外什么都不加载。当我修改代码并在 Chrome 的控制台中运行它时,data最终是一串混乱的字符,我认为这些字符是原始图像数据。

I have been searching for several days now, including on SO, and I have yet to find a solution which does what I need. On the contrary, I have found solutions which simply put the url into the image source using jQuery attr()which isn't what I need.

我已经搜索了几天,包括在 SO 上,但我还没有找到满足我需要的解决方案。相反,我找到了使用 jQuery 简单地将 url 放入图像源的解决方案,attr()这不是我需要的。

If anyone can provide any kind of solution to fix this code, or even perhaps a different and more efficient method of getting all the images, I am open to anything.

如果有人可以提供任何类型的解决方案来修复此代码,或者甚至是获取所有图像的不同且更有效的方法,我对任何事情都持开放态度。

imageArray: http://pastebin.com/03tvpNey

图像阵列http: //pastebin.com/03tvpNey

Regards, Emanuel

问候, 伊曼纽尔

回答by Dave Salomon

If you're using Base64 image data (the string of jumbled characters you mentioned), you'll need to get your img srcto be something like:

如果您使用的是 Base64 图像数据(您提到的混乱字符的字符串),则需要将您的内容img src设置为:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

So your code should be:

所以你的代码应该是:

var imageArray = <?php if (!empty($images)) {echo '["' . implode('", "', $images) . '"]';} else {echo "false";} ?>;
console.log(imageArray);
console.log(imageArray.length);
for (i = 0; i < imageArray.length; i++) {
$.ajax({
    type: 'GET',
    url: imageArray[i],
    dataType: 'image/jpg',
    async: true,
    success: function (data) {
        $("#" + i).attr("src", 'data:image/png;base64,'+data);
    }
});
}

However... I'd be very surprised if loading the images over AJAX and using the Base64 content is any quicker than using a normal <img src="path"/>approach.

但是......如果通过 AJAX 加载图像并使用 Base64 内容比使用正常<img src="path"/>方法更快,我会感到非常惊讶。

The point of AJAX is to fetch some data after the DOM is loaded. All moderns browsers will alreadyfetch images asynchronously. I doubt you'll see any performance gain whatsoever.

AJAX 的目的是在加载 DOM 后获取一些数据。所有现代人的浏览器将已经异步获取的图像。我怀疑你会看到任何性能提升。

I'd suggest the more likely problem is that your 25 images... which I suppose are displayed as thumbnails... are still large, hi-res images. You should save a smaller 'thumbnail' version, and then fetch the hi-res image when/if the user clicks on the thumbnail to view the full-size one.

我建议更可能的问题是你的 25 张图像......我想它们显示为缩略图......仍然是大的高分辨率图像。您应该保存一个较小的“缩略图”版本,然后在/如果用户单击缩略图查看全尺寸图像时获取高分辨率图像。

Notethat an element ID canstart with (or be) a number. This wasn't valid in HTML4, but is perfectly fine in HTML5. However, you might have trouble with CSS rules - so you'd be better off prefixing with a letter (i.e. i1,i2,i3...).

请注意,元素 ID可以以(或为)数字开头。这在 HTML4 中无效,但在 HTML5 中完全没问题。但是,您可能在使用 CSS 规则时遇到问题 - 因此最好在前缀前加上一个字母(即 i1、i2、i3...)。

回答by lharby

Just to update (May 2020) as I have been trying to get images via ajax, with no success despite using the base64 approach.

只是为了更新(2020 年 5 月),因为我一直在尝试通过 ajax 获取图像,尽管使用了 base64 方法但没有成功。

Here is some code I have modified which returns the image as a blob:

这是我修改过的一些代码,它们将图像作为 blob 返回:

const trigger = $('.trigger');
const wrapper = $('#wrapper');
const url = 'https://66.media.tumblr.com/35a8d8dac5c288505b3edb4a52655283/ee225bfce5e62623-af/s1280x1920/fad4e25562ce1b05c69dc8cc8da5a9a12d26a1aa.jpg';

trigger.on('click', () => {
    $.ajax({
       url,
       xhrFields:{
          responseType: 'blob'
       },
       success (data) {
          const url = window.URL || window.webkitURL;
          const src = url.createObjectURL(data);
          wrapper.attr('src', src);
       }
   });
});

Working example here: http://jsfiddle.net/lharby/Ljwa1yhd/

这里的工作示例:http: //jsfiddle.net/lharby/Ljwa1yhd/

I realise this is slightly different to the OP request, but I found my way here searching 'get images via ajax jquery' so I hope it is of help. And as I could not get the base64 method to work, I thought an example might be useful.

我意识到这与 OP 请求略有不同,但我在这里找到了搜索“通过 ajax jquery 获取图像”的方法,所以我希望它有所帮助。由于我无法使用 base64 方法,我认为一个示例可能有用。

回答by Haring10

I had an issue with this a while ago, I used this code:

不久前我遇到了这个问题,我使用了以下代码:

function loadImage(path, width, height, target) {
    var loaded = true;
    $('<img src="' + path + '">').load(function () {
        if (loaded) {
            $(this).css('maxWidth', width).css('maxHeight', height).appendTo(target);
            loaded = false;
        }
    });
}

UPDATE:

更新:

using your images array:

使用您的图像数组:

["20151107_140328.jpg", "20151107_140329.jpg", "20151107_141113.jpg", "20151107_141114.jpg", "20151107_141439.jpg", "20151107_141447.jpg", "20151107_141500.jpg", "20151107_205509.jpg", "20151107_205512.jpg", "20151107_213703.jpg", "20151107_213708.jpg", "20151107_213823.jpg", "20151108_143256.jpg", "20151108_143258.jpg", "20151108_143320.jpg", "20151108_143322.jpg", "20151108_143339.jpg", "20151108_143340.jpg", "20151108_143419.jpg", "20151108_143422.jpg", "20151108_143433.jpg", "20151108_143435.jpg", "20151108_143443.jpg", "20151108_143445.jpg"]

You can do this:

你可以这样做:

var image_array = ["20151107_140328.jpg", "20151107_140329.jpg", "20151107_141113.jpg", "20151107_141114.jpg", "20151107_141439.jpg", "20151107_141447.jpg", "20151107_141500.jpg", "20151107_205509.jpg", "20151107_205512.jpg", "20151107_213703.jpg", "20151107_213708.jpg", "20151107_213823.jpg", "20151108_143256.jpg", "20151108_143258.jpg", "20151108_143320.jpg", "20151108_143322.jpg", "20151108_143339.jpg", "20151108_143340.jpg", "20151108_143419.jpg", "20151108_143422.jpg", "20151108_143433.jpg", "20151108_143435.jpg", "20151108_143443.jpg", "20151108_143445.jpg"];

for(var i = 0; i < image_array.length; i++) {
    loadImage(image_array[i], <width>, <height>, <container targeted>);
}

and in the imageLoad function:

在 imageLoad 函数中:

function loadImage(path, width, height, target) {
    var loaded = true;
    $('<img src="/path/to/image/' + path + '">').load(function () {
        if (loaded) {
            $(this).css('maxWidth', width).css('maxHeight', height).appendTo(target);
            loaded = false;
        }
    });
}

回答by Suchit kumar

Change your ids to id1,id2or something similar from 1,2and in success use this:

将您的 id 更改为id1,id2或类似的内容1,2并成功使用:

            $("#id" + i).attr("src", data);

see why id should not start from a number:What are valid values for the id attribute in HTML?

看看为什么 id 不应该从数字开始:HTML 中 id 属性的有效值是什么?