Py学习  »  Jquery

如何在javascript/jquery中刷新div

Anoop • 4 年前 • 469 次点击  

我正在上传个人资料图片

它保存到s3 bucket并返回url

图片更新后,需要刷新页面以显示新图像

我需要在图片更新后更新那个div

$("#profile-pic-upload").change(function () {
    var input_detail = this;
    console.log(input_detail);
    var data = new FormData();
    var file = this.files[0];
    data.append("file", file);
    $.ajax({
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        url: $("#profile-file-upload").data('action'),
        cache: false,
        success: function (data, status) {
            if (data['status'] == true) {
                toastr.success(data.msg);
                $('#imagePreview').css('background-image', 'url('+data.avatar+')');
            }
            else {
                toastr.error(data.msg);
            }
        }
    });
});

这是我的HTML

<div class="avatar-preview">
    {% if user_profile.avatar %}
        <div id="imagePreview" style="background-image: url('{{user_profile.avatar}}');"></div>
    {% else %}
        <div id="imagePreview" style="background-image: url('{% static 'assets/img/user-64x.png' %}');"></div>
    {% endif %}
</div>

在上面的代码中,我从data.avatar获取图像url

但我的问题是只更新一次

例如,如果没有更新的图像,它将得到更新

如果在我更新为新的用户配置文件中有一个图像,那么它会上传到s3 bucket,但不会显示在div中。我需要刷新页面以便在那里显示它

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55433
 
469 次点击  
文章 [ 1 ]  |  最新文章 4 年前
jeprubio
Reply   •   1 楼
jeprubio    4 年前

在成功回调中更改:

$('#imagePreview').css('background-image', 'url('+data.avatar+')');

var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.avatar + '?random=' + randomId + ')');

你可以使用任意的randomId来强制刷新图像,我选择使用当前的时间戳。