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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Displaying json images on a webpage

  • 06-05-2022 9:30pm
    #1
    Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 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: 839 ✭✭✭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: 81,083 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: 839 ✭✭✭mk7r


    Not a problem



Advertisement