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

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

ie:

用户在默认页面上查看图像 用户上传新图像 页面上的默认图像没有改变(我假设这是由于文件名相同,浏览器使用缓存版本)

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

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

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

非常感谢任何帮助。


当前回答

如果您需要刷新确切的URL,而您的浏览器已经缓存了图像,那么您可以使用AJAX和请求头迫使浏览器下载新的副本(即使它还没有过期)。你可以这样做:

var img = $("#myimg");
var url = img.attr("src");
$.ajax({
    url: url,
    headers: { "Cache-Control": "no-cache" }
}).done(function(){
    // Refresh is complete, assign the image again
    img.attr("src", url);
});

其他方法对我都不起作用,因为在查询字符串中添加令牌会下载新图像,但它不会使缓存中的旧URL中的图像无效,因此未来的请求将继续显示旧图像。旧的URL是唯一发送到浏览器的URL,服务器指示客户机缓存图像的时间超过了它应该缓存的时间。

如果这仍然不能为您刷新图像,看看这个答案是否有帮助。有关更多信息,这里是关于Cache-Control请求头的文档。

其他回答

为了绕过缓存并避免向图像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);
}

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

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

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

您是否尝试重置图像容器html。当然,如果是浏览器在缓存,那么这就没有帮助了。

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

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

服务器正在缓存映像 jQuery不会触发或至少不会更新属性

说实话,我觉得是第二。如果我们能看到更多的jQuery,这将会容易得多。但是首先,请尝试先删除该属性,然后重新设置它。看看这是否有帮助:

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

即使这是有效的,张贴一些代码,因为这不是最佳的,在我看来:-)

这工作很棒!但是,如果您多次重载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());
});