Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

javascript - Why is my JS file not getting my json code?

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

question from:https://stackoverflow.com/questions/65861801/why-is-my-js-file-not-getting-my-json-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) { 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...