Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Displaying json images on a webpage

Options
  • 06-05-2022 10:30pm
    #1
    Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,381 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 Posts: 759 ✭✭✭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 Posts: 80,381 Mod ✭✭✭✭Sephiroth_dude


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



  • Registered Users Posts: 759 ✭✭✭mk7r


    Not a problem



Advertisement