最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Force background image reload - Stack Overflow

programmeradmin0浏览0评论

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.

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.png so this would be same but my php page update image content so need refresh this url every time while image update.

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.

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.png so this would be same but my php page update image content so need refresh this url every time while image update.

Share Improve this question asked Dec 11, 2013 at 12:54 Affan AhmadAffan Ahmad 4514 gold badges9 silver badges22 bronze badges 1
  • You have to edit image url like here: stackoverflow.com/a/2104998/3090180 – apo Commented Dec 11, 2013 at 12:57
Add a comment  | 

3 Answers 3

Reset to default 19

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

http://yourdomain.jpg?random=1239308234

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

const 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}`);
    },
);

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()));},

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:

$(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})]
        }
    );
});
发布评论

评论列表(0)

  1. 暂无评论