如何在 jQuery 中重新加载/刷新元素(图像)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2104949/
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-26 12:47:03  来源:igfitidea点击:

How to reload/refresh an element(image) in jQuery

jquery

提问by Alexis Abril

Is it possible to reload an image with an identical file name from a server using jQuery?

是否可以使用 jQuery 从服务器重新加载具有相同文件名的图像?

For example, I have an image on a page, however, the physical image can change based on user actions. Note, this does not mean the file name changes, but the actual file itself.

例如,我在页面上有一个图像,但是,物理图像可以根据用户操作而改变。请注意,这并不意味着文件名更改,而是实际文件本身。

ie:

IE:

  • User views image on default page
  • User uploads new image
  • Default image on page does not change(I assume this is due to the file name being identical, the browser uses the cached version)
  • 用户在默认页面上查看图像
  • 用户上传新图片
  • 页面上的默认图像不会改变(我认为这是由于文件名相同,浏览器使用缓存版本)

Regardless of how often the code below is called, the same issue persists.

不管下面的代码被调用的频率如何,同样的问题仍然存在。

$("#myimg").attr("src", "/myimg.jpg");

In the jQuery documentation, the "load" function would be perfect if it had a default method of firing the event as opposed to binding a callback function to a successful/complete load of an element.

在 jQuery 文档中,如果“加载”函数具有触发事件的默认方法,而不是将回调函数绑定到元素的成功/完整加载,则它会是完美的。

Any assistance is greatly appreciated.

非常感谢任何帮助。

回答by jay

It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:

听起来是您的浏览器缓存了图像(我现在注意到您在问题中写道)。您可以通过传递一个额外的变量来强制浏览器重新加载图像,如下所示:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());

回答by Kaleb Brasee

It's probably not the best way, but I've solved this problem in the past by simply appending a timestamp to the image URL using JavaScript:

这可能不是最好的方法,但我过去通过使用 JavaScript 简单地将时间戳附加到图像 URL 解决了这个问题:

$("#myimg").attr("src", "/myimg.jpg?timestamp=" + new Date().getTime());

Next time it loads, the timestamp is set to the current time and the URL is different, so the browser does a GET for the image instead of using the cached version.

下次加载时,时间戳设置为当前时间并且 URL 不同,因此浏览器对图像执行 GET,而不是使用缓存版本。

回答by Kordonme

This could be one of the two problems you mention yourself.

这可能是您自己提到的两个问题之一。

  1. The server is caching the image
  2. The jQuery does not fire or at least doesn't update the attribute
  1. 服务器正在缓存图像
  2. jQuery 不会触发或至少不会更新属性

To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:

老实说,我认为这是第二名。如果我们能看到更多的 jQuery 会容易很多。但首先,请尝试先删除该属性,然后再重新设置。只是为了看看这是否有帮助:

$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");

Even if this works, post some code since this is not optimal, imo :-)

即使这有效,也要发布一些代码,因为这不是最佳的,imo :-)

回答by Radu

with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:

一行无需担心将图像 src 硬编码到 javascript 中(感谢 jeerose 的想法:

$("#myimg").attr("src", $("#myimg").attr("src")+"?timestamp=" + new Date().getTime());

回答by sEver

To bypass caching andavoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.

要绕过缓存避免向图像 url 添加无限时间戳,请在添加新时间戳之前去除前一个时间戳,我就是这样做的。

//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);

function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
    //get the src attribute
    source = jQuery(".xyro_refresh").attr("src");
    //remove previously added timestamps
    source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
    //prep new src attribute by adding a timestamp
    new_source = source + "?timestamp="  + new Date().getTime();
    //alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
    //set the new src attribute
    jQuery(".xyro_refresh").attr("src", new_source);
}

回答by kasper Taeymans

This works great! however if you reload the src multiple times, the timestamp gets concatenated to the url too. I've modified the accepted answer to deal with that.

这很好用!但是,如果您多次重新加载 src,时间戳也会连接到 url。我已经修改了接受的答案来解决这个问题。

$('#image_reload_button').on('click', function () {
    var img = $('#your_image_selector');
    var src = img.attr('src');
    var i = src.indexOf('?dummy=');
    src = i != -1 ? src.substring(0, i) : src;

    var d = new Date();
    img.attr('src', src + '?dummy=' + d.getTime());
});

回答by Matti Lyra

Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.

您是否尝试过重置图像容器 html。当然,如果是浏览器缓存,那么这将无济于事。

function imageUploadComplete () {
    $("#image_container").html("<img src='" + newImageUrl + "'>");
}

回答by Kulbhushan Chaskar

Some times actually solution like -

有时实际上解决方案如 -

$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));

also not refresh src properly, try out this, it worked for me ->

也没有正确刷新 src,试试这个,它对我有用 ->

$("#Image").attr("src", "dummy.jpg");
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));

回答by user3506298

Using "#" as a delimiter might be useful

使用“#”作为分隔符可能很有用

My images are kept in a "hidden" folder above "www" so that only logged users are allowed access to them. For this reason I cannot use the ordinary <img src=/somefolder/1023.jpg>but I send requests to the server like <img src=?1023>and it responds by sending back the image kept under name '1023'.

我的图像保存在“www”上方的“隐藏”文件夹中,以便仅允许登录的用户访问它们。出于这个原因,我不能使用普通的,<img src=/somefolder/1023.jpg>但我像向服务器发送请求一样<img src=?1023>,它通过发回名称为“1023”的图像进行响应。

The application is used for image cropping, so after an ajax request to crop the image, it is changed as content on the server but keeps its original name. In order to see the result of the cropping, after the ajax request has been completed, the first image is removed from the DOM and a new image is inserted with the same name <img src=?1023>.

该应用程序用于图像裁剪,因此在裁剪图像的 ajax 请求后,它在服务器上更改为内容,但保留其原始名称。为了查看裁剪的结果,在ajax请求完成后,从DOM中移除第一张图片,并插入一个同名的新图片<img src=?1023>

To avoid cashing I add to the request the "time" tag prepended with "#" so it becomes like <img src=?1023#1467294764124>. The server automatically filters out the hash part of the request and responds correctly by sending back my image kept as '1023'. Thus I always get the last version of the image without much server-side decoding.

为了避免兑现,我在请求中添加了以“#”开头的“时间”标签,因此它变成了<img src=?1023#1467294764124>. 服务器自动过滤掉请求的哈希部分,并通过发回我保留为“1023”的图像来正确响应。因此,我总是在没有太多服务器端解码的情况下获得图像的最新版本。

回答by slp

I may have to reload the image source several times. I found a solution with Lodashthat works well for me:

我可能需要多次重新加载图像源。我用Lodash找到了一个适合我的解决方案:

$("#myimg").attr('src', _.split($("#myimg").attr('src'), '?', 1)[0] + '?t=' + _.now());

An existing timestamp will be truncated and replaced with a new one.

现有时间戳将被截断并替换为新时间戳。