如何从JSON API调用值

时间:2016-02-23 10:42:24

标签: jquery json ajax api

我有一个这样的JSON文件保存为runs.json,我想使用ajax调用json文件,但我实际想从json调用的值没有反复显示我未定义

{
    "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.

2 个答案:

答案 0 :(得分:0)

 var first = result.data.Athletes[0].FirstName;
 var last = result.data.Athletes[0].LastName;

这应该对你有用

答案 1 :(得分:0)

你必须将它分解为嵌套的方法。

data
     Athletes
             FirstName

因此:

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