如何在文档就绪上使用ajax加载图像

时间:2017-10-11 11:26:57

标签: javascript jquery html css ajax

$(document).ready(function() {
initfun();
console.log("initalized !");
});

function initfun() {
var basepath = document.location.href + "/wp-content/themes/breviter/assets/tmbdapicalls.py";
$.ajax({
    type: "get",
    url: "http://127.0.0.1:5000/guestSuggestion",
    datatype: "json",
    success: function(response) {
        var output = response;
        //console.log(JSON.stringify(output));
        var json = JSON.parse(output);
        var backpostimage = "https://image.tmdb.org/t/p/w600" + json["results"][0]["backdrop_path"];
        console.log(backpostimage);
        document.getElementById("page-canvas").style = 'background-image: ' + backpostimage + ';background-repeat: no-repeat; background-size:100% 100%;'

    }
})
}

我使用上面的代码来设置元素的css背景,但由于某种原因,我无法设置背景图像参数,其他参数已成功设置,如下所示

<div id="page-canvas" class="page-wrapper" style="background-repeat: no-repeat; background-size: 100% 100%;">

2 个答案:

答案 0 :(得分:4)

您尚未将图片路径传递到url()

中的background-image功能
document.getElementById("page-canvas").style = 'background-image: ' + backpostimage + ';background-repeat: no-repeat; background-size:100% 100%;'

正确

document.getElementById("page-canvas").style = 'background-image: url(' + backpostimage + ');background-repeat: no-repeat; background-size:100% 100%;'

答案 1 :(得分:4)

您不应该使用样式设置整个字符串,只需设置图像

document.getElementById("page-canvas").style.backgroundImage = 'url("' + backpostimage + '")';

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image