简体   繁体   中英

How to call values from a JSON API

I have a JSON file like this saved as runs.json and I would like to make a call to the json file using ajax but the value i actually wanted from the json is not showing repeatedly am getting undefined

{
    "status": "true",
    "Content-Range": {
        "AthletesRange": [
            {
                "first": "1",
                "last": "1",
                "max": "1"
            }
        ]
    },
    "data": {
        "Athletes": [
            {
                "AthleteID": "600",
                "FirstName": "Edward",
                "LastName": "HAWTHORNE",
                "HomeRunID": "1",
                "Sex": "M",
                "CountryCode": "97",
                "Avatar": "images.parkrun.com/app/general/parkrun_default_avatar_200x200.png"
            }
        ]
    },
    "links": [
        {
            "rel": "self",
            "href": "\"/v1/athletes/600?offset=0&limit=100\""
        }
    ],
    "timestamp": 1456223662,
    "originalQryTime": 1456223662
}

My AJAX call is like this

<script>

    $(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "runs.json",
        dataType: 'json',
       success: function(result){
        var first = result.FirstName;
        var last = result.LastName;
        $('#runner-name').append(' Welcome ' + first +  last );
    }
            });
    });
</script>

<body>
 <div>
     <h1 id="runner-name"></h1>
 </div>
</body>

But am continually getting undefined as the value passed out, I would like if anyone could help me with this JSON call because i need the FirstName and LastName of the particular Athlete.
 var first = result.data.Athletes[0].FirstName;
 var last = result.data.Athletes[0].LastName;

This should work for you

You have to break it down into a nested like approach.

data
     Athletes
             FirstName

Therefore:

var returnedResult = result.data.Athletes[i].FirstName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM