使用AJAX从嵌套的JSON对象中检索值

时间:2014-07-24 17:36:27

标签: jquery ajax json

这是我的AJAX请求可以正常运行:

$.ajax
({
    url: 'api.php',
    type: 'GET',
    data: {search_term: data},
    dataType: 'JSON',
    success: function(data) {
        $('#div').html('<p>Constituency: ' + data + '</p>');
    },
    error: function() {
        $('#div').html('<p>Something went wrong. Please try again later.</p>');
    }
});

我如何构建此基础以允许我返回嵌套值而不仅仅是data?例如,我如何从此返回constituency_name

{"results": { "constituencies": [{"constituency_name": "Holborn and St Pancras", "member_name": "Frank Dobson", "member_party": "Labour", "member_biography_url": "http://www.parliament.uk/biographies/commons/Frank-Dobson/180", "member_website": "", "uri": "http://findyourmp.parliament.uk/constituencies/holborn-and-st-pancras.json" } ], "members": [] }}

现在如果有两个元素都叫constituency_name,那么该怎么办?

{"results": { "constituencies": [{"constituency_name": "Cities of London and Westminster", "member_name": "Mark Field", "member_party": "Conservative", "member_biography_url": "http://www.parliament.uk/biographies/commons/Mark-Field/1405", "member_website": "http://www.markfieldmp.com", "uri": "http://findyourmp.parliament.uk/constituencies/cities-of-london-and-westminster.json" } , {"constituency_name": "Westminster North", "member_name": "Ms Karen Buck", "member_party": "Labour", "member_biography_url": "http://www.parliament.uk/biographies/commons/Ms-Karen-Buck/199", "member_website": "http://www.karenbuck.org.uk/", "uri": "http://findyourmp.parliament.uk/constituencies/westminster-north.json" } ], "members": [] }}

修改

在尝试了tymeJV的回复之后,这是我的代码:

$.ajax
({
    url: 'api.php',
    type: 'GET',
    data: {search_term: data},
    dataType: 'JSON',
    success: function(data) {
        for (var i = 0; i < data.results.constituencies.length; i++) {
        var name = data.results.constituencies[i]["constituency_name"]; //name for this element in the array
            $('#div').html('<p>Constituency: ' + name + '</p>');
        }
    },
    error: function() {
        $('#div').html('<p>Something went wrong. Please try again later.</p>');
    }
});

我收到以下错误:

  

未捕获的TypeError:无法读取属性&#39;选区&#39;未定义的

3 个答案:

答案 0 :(得分:1)

你可以遍历你的设置并做你需要的事情:

for (var i = 0; i < data.results.constituencies.length; i++) {
    var name = data.results.constituencies[i]["constituency_name"]; //name for this element in the array
    //do stuff
}

答案 1 :(得分:0)

您需要做的就是像这样将数据解析为json对象

var Obj = JSON.parse(data);

现在,如果你需要constituency_name,你可以这样做

$('#div').html('<p>Constituency: ' + Obj.results.constituencies[0].constituency_name + '</p>');

答案 2 :(得分:0)

您可以使用jQuery的$ .each函数迭代列表并返回constituency_name对象:

$.each(data.results.constituencies, function(index, element) {
    console.log(element.constituency_name);
});

这将迭代每个选区名称并在控制台中打印。

查看jQuery .each() Documentation