简体   繁体   中英

How to fetch image from api

I got the image name in pic variable , but now i'm blank how to show that image in front end .

<script>
$.getJSON(`https://openlibrary.org/authors/<%= match %>.json`, function(data) {


    var text = `<tr><td>${data.name}</td>
                    <td>${data.bio}</td>
                    <td>${data.alternate_names}</td>
                <td>${data.birth_date}</td></tr>`
    var pic = `${data.photos}`
    $(".mypanel").html(text);
    $(".picpanel").html(pic);

});

There are several ways, you can simply implement them in img tags :

$(".picpanel").append("<img src='" + pic + "'>");

you can also implement it on a element as background :

$(".picpanel").css('background-image', 'url(' + pic + ')');

Edit: wanted solution :

<script>
$.getJSON(`https://openlibrary.org/authors/<%= match %>.json`, function(data) {


    var text = `<tr><td>${data.name}</td>
                <td>${data.bio}</td>
                <td>${data.alternate_names}</td>
            <td>${data.birth_date}</td></tr>`
    var pic = data.photos;
    $(".mypanel").html(text);
    if(pic!==undefined && pic.length>0){
        $(".picpanel").html("<img src='//covers.openlibrary.org/a/id/" + pic[0] + "-M.jpg'>");
    }
});
</script>

就您当前的情况而言,我想可能是这样。

$(".picpanel").html("<img src='" + pic + "' />");

Here is your complete solution

   <script>
          $.getJSON(`https://openlibrary.org/authors/<%= match %>.json`, function(data) {


    var text = `<tr><td>${data.name}</td>
                    <td>${data.bio}</td>
                    <td>${data.alternate_names}</td>
                <td>${data.birth_date}</td></tr>`
    var pic = `${data.photos[0]}`
    $(".mypanel").html(text);
    var add =pic+'-M.jpg'
    console.log(add);
    $(".picpanel").append("<img src='https://covers.openlibrary.org/a/id/" + add + "'>");
});

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