Consume Javascript JSON data [closed]

0

I need a help with javascript. I'm trying to show in my index.html the data I'm consuming from a json. However when opening the index and waiting for the document to be loaded the items come with undefined.

$(document).ready(function () {
    var products = "";
    var url = "https://api.myjson.com/bins/10p600";

    $.ajax({
        url: url,    
        dataType: "json",
        success: function (response) {
            if(response[0].erro) {
                $("h2").html(response[0].erro);
            }else {
                for(var i = 0; i < response.length; i++) {
                    products += "<div>";
                    products += "<div>" + response[i].imageName + "</div>";
                    products += "<h4>" + response[i].name + "</h4>";
                    products += "<p>" + response[i].price + "</p>";
                    products += "<p>" + response[i].paymentConditions + "</p>";    
                    products += "</div>";               
                }
                
                $("#myproducts").html(products);
            }
        }
    });
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Teste Front-End</title>
</head>
<body>
    <div id="myproducts"></div>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><scripttype="text/javascript" src="teste.js"></script>
</body>
</html>
    
asked by anonymous 05.01.2019 / 15:07

1 answer

2

You are accessing keys that do not exist in JSON, so you get undefined.

The structure of JSON is:

[
    data: {
        item: {...},
        recommendation: [{...}, {...}, {...}, ...],
        widget: {
            size: 10
        }
    }
]

What you want to access in your code is response[i].data.item.imageName , response[i].data.item.name , response[i].data.item.price and response[i].data.item.productInfo.paymentConditions

edit

Or if you are trying to access the recommendations would be response[0].data.recommendation[i].imageName , response[0].data.recommendation[i].name , etc.

    
05.01.2019 / 15:26