Using AJAX to extract data from a JSON file

so I am trying to read data from my JSON file and display it on a web page using HTML. It would work with simple keys with this particular database, it wouldn't work for me.

JSON:

var carInfo = [
{
    carId: 1,
    carPrice : 15.00,
},
{
    carId: 2,
    carPrice : 25.00,
}
];

      

JS:

$(document).ready(function() {

    $.getJSON("vehicle_data.json", function(data) {

        $.each(data.carInfo, function() {

            $("ul").append("<li>Car ID: "+this[carInfo[0].carId]);

        });         
    });     
});

      

HTML:

<html>
<body>
<ul></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="json_data_retrieve.js"></script>
</body>
</html>

      

+3


source to share


2 answers


Invalid JSON file. This is a JS script.

var carInfo = [
    {
        carId: 1,
        carPrice : 15.00,
    },
    {
        carId: 2,
        carPrice : 25.00,
    }
];

      

Try the following:

{
    "carInfo": 
    [
        {
            "carId": 1,
            "carPrice": 15
        },
        {
            "carId": 2,
            "carPrice": 25
        }
    ]
}

      

Update:
You can download this script as a script source in HTML. It should be a .js file.



<script src="vehicle_data.js"></script>

      

If you need to load it dynamically use the jQuery method $.getScript

. It doesn't matter if it has .json extensions, because it will evaluate as a script.

$(document).ready(function() 
{
    $.getScript("vehicle_data.json", function() 
    {
        // Pay attention. In this case, you work with carInfo 
        // variable because it has been executed as a script, 
        // but not loaded as a JSON file.
        $.each(carInfo, function()             {
            $("ul").append("<li>Car ID: " + this[carInfo[0].carId]);
        });         
    });     
});

      

However, it's weird that someone gives you a .json file with a JS declaration and tells you that you should execute it, but shouldn't rename it or load it as a script.

+4


source


It looks like you are trying to iterate over the parent object within yourself. try it



$.each(data.carInfo, function(k, v) {

        $("ul").append("<li>Car ID: "+v.carId);

    });   

      

-2


source







All Articles