1

I'm trying to use json code in an HTML table, but the javascript file is not getting the json code. It's valid json and everything else in the javascript file is working correctly, but the $.getJSON is not called at all.

$(document).ready(function() { 

    $.getJSON("objects.json", function(data) { 
        var stars = ''; 
        $.each(data, function (i, f) { 

            stars += '<tr>' + 
                '<td>' + f.name + '</td>' + 
                '<td>' + f.orbiting + '</td>' + 
                '</tr>'; 
        }); 
        $('#table').append(stars); 
    }); 
}); 

Nothing after the function(data) happens at all.

This is the objects.json file, which is located in the same folder as the main.js file:

{
"stars": [
    {
      "name": "Sun",

      .......

      "siderealRotation": 609.12,
      "obliquityToOrbit": 7.25,
      "speedRelativeToStars": 19.4,
      "orbiting": "Galactic Center",

      ....

Thank you for any help

joerup2004
  • 33
  • 7
  • You are trying to loop over data which is an object that contains starts array, also, please mention more details if there's any console errors – Zac Jan 23 '21 at 16:52
  • Are you loading your page from `localhost`? [$.getJSON will only work if your objects.json is being served over http and not the local file protocol.](https://stackoverflow.com/questions/8533078/getjson-not-working-with-local-json-file) – tklg Jan 23 '21 at 16:59
  • Hey thanks for responding. There are no console errors, and I changed it to loop over data.stars, but the problem still is that nothing in the function is called whatsoever. I even tried adding a hard-coded "$('#table').append("hhhhh");" and still not even that is called. – joerup2004 Jan 23 '21 at 17:01
  • Would I be able to load it over GitHub or something? – joerup2004 Jan 23 '21 at 17:05
  • I tried using json bin, still nothing working :( – joerup2004 Jan 23 '21 at 17:15

1 Answers1

0

In you JSON is a Object. data.stars is a array.

so use

$.each(data.stars, function (i, f) { 

instead of

$.each(data, function (i, f) { 
prasanth
  • 22,145
  • 4
  • 29
  • 53