简体   繁体   中英

replacing css background image after uploading that photo via Ajax

I have an element which when I click It opens input dialog and uploads the selected photo. the server responds the request with 4 items as a JSON OBJECT : NAME,TYPE,HEIGHT,WIDTH .

The thing I want is after a successful ajax upload process, reload/refresh the element background with the newly uploaded photo. so far I've don these:

JS:

$(document).ready(function() {
    $("input[name!='photo_1']").parents('.fileinput-wrapper').find(".label").remove();

    $("input[type=file]").on('change',function(){
        $(this).parents('label').find('.fileinput-preview').css('background','url(http://localhost/project/assets/images/ajax-loader.GIF) no-repeat center center');
        var selectedElement = this;
        var name = $(this).attr('name').toString();
        $('#upload').ajaxSubmit({
            dataType:'json',
            data: {name:name},
            beforeSubmit:function(){
                $(selectedElement).parents('label').find('input[type=file]').attr('disabled','disabled');
            },
            success: function(data) {
                $(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/loading.png') no-repeat center center");
                $.each(data, function(index, item) {
                    $(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/uploads/"+ item.NAME +") no-repeat center center");//**replacing part**
                });
                $(selectedElement).parents('label').find('input[type=file]').removeAttr('disabled');
                return false;
            },
            error : function(xhr) {
                alert(xhr.responseText);
                return false;
            }
        });
    });

});

the thing is it replaces the background right but the image doesn't load and shows a blank. What should I do?

You are missing a single ' :

.css('background',"url('http://localhost/project/uploads/"+ item.NAME +")

Should be

.css('background',"url(http://localhost/project/uploads/"+ item.NAME +")

The url parameter does not need '' , url(path/to/file.jpg) works fine. You are only setting one, though. Also, does item.name contain the file extesion?

Check with the dom inspector what url is being set after the success, or do a console log of the full string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM