我无法获得使用XmlHttpRequest找到的URL的图像

时间:2018-07-19 22:17:54

标签: javascript json xmlhttprequest

我正在尝试通过XmlHttpRequest获取图像网址,并像“ img”标记的“ src”属性一样使用它。那是我的计划:

function populaLista() {

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8080/artes');

ourRequest.onload = function() {
    var ourData = ourRequest.responseText.toString();
    var jsonResposta = JSON.parse(ourData);

    if (ourData.length > 0) {

        document.getElementById("paragrafo1").innerHTML = jsonResposta.url;

        var tabela = document.createElement("TABLE");
        var corpoTabela = document.createElement("TBODY");
        var tr = document.createElement("TR");
        var td = document.createElement("TD");
        var imagem = document.createElement("IMG");
        var urlImg = document.createTextNode(jsonResposta.url).toString();
    //  var urlImg = "https://mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg";

        document.getElementById("paragrafo").innerHTML = typeof urlImg;

        imagem.setAttribute("src",urlImg);
        td.appendChild(imagem);
        tr.appendChild(td);
        corpoTabela.appendChild(tr);
        tabela.appendChild(corpoTabela);

        document.getElementById("tabeladeImagens").appendChild(tabela);

    } else {
        document.getElementById("paragrafo").innerHTML = "item não encontrado";
    }

};
ourRequest.send();

问题是:当我在img标签上使用请求的结果时,看不到图像,但是如果我在创建的字符串var中使用相同的url,则可以正常看到。

<html>
<head>
<meta charset="ISO-8859-1">

</head>
<body onload="populaLista()">

    <p id="paragrafo"></p>
    <p id="paragrafo1"></p>

    <div id="tabeladeImagens" class="logoHome"></div>

    <script src="main.js"></script>

</body>
</html>

json响应:

{id : 38, url : "//mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg"}

0 个答案:

没有答案