javascript 强制背景图像重新加载

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

Force background image reload

javascriptjquery

提问by Affan Ahmad

I need force to div background image refresh while my ajax request success My div background image url same not change but image content change while ajax success.how can i refresh background url.

我的 ajax 请求成功时,我需要强制刷新 div 背景图像 我的 div 背景图像 url 没有变化,但图像内容在 ajax 成功时发生了变化。我如何刷新背景 url。

JavaScript

JavaScript

    $.ajax({
 url: "editor/savemapimage.php",
 type:"POST",
 data:{imagevalue : urlimage},
success:function(data){$(".map_canvas").css("background-image","url("+data+")");},

Above code if result data is string something map.pngso this would be same but my php page update image content so need refresh this url every time while image update.

上面的代码如果结果数据是字符串,map.png那么这将是相同的,但我的 php 页面更新图像内容,因此每次图像更新时都需要刷新此 url。

回答by Bas van Dijk

You can add an unique ID to the end of the image url like:

您可以在图像 url 的末尾添加一个唯一 ID,例如:

http://yourdomain.jpg?random=1239308234

If the ID is unique the browser will consider it a new resource and will reload the image.

如果 ID 是唯一的,浏览器会将其视为新资源并重新加载图像。

var randomId = new Date().getTime());
 $.ajax({
   url: "editor/savemapimage.php",
   type: "POST",
   data: {
     imagevalue: urlimage
   },
   success: function (data) {
     $(".map_canvas").css("background-image", "url(" + data + "?random=" + randomId + ")");
   },

回答by Ruben Nagoga

You should add some random query to your background image and set it again

您应该向背景图像添加一些随机查询并重新设置

$.ajax({
    url: "editor/savemapimage.php",
    type:"POST",
    data:{imagevalue : urlimage},
    success:function(data){$(".map_canvas").css("background-image","url("+data+"?random="+ new Date().getTime()));},

回答by garrettlynch

For anyone working with Literally Canvas you may get this same issue. It was certainly occurring for me in Chrome. Bas van Dijk's solution works well so just use it like so:

对于任何使用 Literally Canvas 的人,您可能会遇到同样的问题。在 Chrome 中,这对我来说肯定发生了。Bas van Dijk 的解决方案效果很好,所以只需像这样使用它:

$(document).ready(function() {

    //background image (add random variable to stop caching)
    var backgroundImage = new Image()
    backgroundImage.src = "my-image.png?r=" + new Date().getTime();

    var lc = LC.init(
        document.getElementsByClassName('literallycanvasdiv')[0],
        {
            backgroundColor: 'whiteSmoke', 
            backgroundShapes: [LC.createShape('Image', {x: 10, y: 10, image: backgroundImage, scale: 1})]
        }
    );
});