Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Displaying json images on a webpage

  • 06-05-2022 10:30PM
    #1
    Moderators, Computer Games Moderators, Social & Fun Moderators, Paid Member Posts: 81,191 Mod ✭✭✭✭


    Really stuck, how can I display images on a webpage from json ? don't know what I'm missing


    fetch('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=3415&camera=mast&page=1&api_key=DEMO_KEY')
    .then(response => response.json())
    .then(data => {
        console.log(data)
    
    
        let elem1 = document.getElementById('image')
        data.photos.forEach(element => console.log(element.img_src))
    
    
        elem1.innerHTML += `<div class="image-list"><img src ="${data.img_src}"</div>`
        
    
    
        
    
    
    
        
    })
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div id="image"></div>
        <script src="script.js"></script>
    </body>
    </body>
    </html>
    




Comments

  • Registered Users, Registered Users 2 Posts: 1,052 ✭✭✭mk7r


    You arent inserting the image src is your problem.

    For your elem1.innerHtml src, the value would be: data.photos[1].img_src to get the second image for example. To get all the images you would need to create a for loop like so:

    let elem1 = document.getElementById('image')

      data.photos.forEach(element => elem1.innerHTML += `<div class="image-list"><img src ="${element.img_src}"</div>`)



    Although this is a neater way of doing it:

    let imageContainer = document.getElementById('image')

      data.photos.forEach(element => imageContainer.innerHTML += `<img src ="${element.img_src}"</div>`)



  • Moderators, Computer Games Moderators, Social & Fun Moderators, Paid Member Posts: 81,191 Mod ✭✭✭✭Sephiroth_dude


    Thanks so much for you help! was at it all day and could not figure it out.



  • Registered Users, Registered Users 2 Posts: 1,052 ✭✭✭mk7r


    Not a problem



Advertisement