使用JSON格式数据使用JQuery AJAX填充HTML表:如何从循环中的变量访问数据?

时间:2015-09-18 20:46:26

标签: jquery html json ajax

我有从JSON返回的以下WCF RESTful Service数据。

{"Cities":["LUSAKA","HARARE"],"Countries":["ZAMBIA","ZIMBABWE"]}

我正在尝试使用此数据填充以下HTML表。

<table id="location" border='1'>
    <tr>
        <th>Countries</th>
         <th>Cities</th>
    </tr>
</table>

以下代码有效,但它依赖于国家或城市的索引,我无法访问anonymous function中项目变量的数据。

var trHTML = '';

$.each(data.Countries, function (i, item) {

trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';

});

$('#location').append(trHTML);

但是,如果我尝试访问这样的数据,它就不起作用:

$.each(data.d.results,function(d, item){ 

    $("#location tbody").append(
                "<tr>"
                  +"<td>"+item.Countries+"</td>"
                  +"<td>"+item.Cities+"</td>"
                +"</tr>" )
            })

如何使用上面循环函数中的item变量访问数据?

以下是完整的工作代码:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>WCF Client</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

</head>

<body>

<table id="location" border='1'>
    <tr>
        <th>Countries</th>
         <th>Cities</th>
    </tr>
</table>

<script>

var service = 'http://localhost/DistributedDataSystem/Service.svc/';

$(document).ready(function(){

    jQuery.support.cors = true;

    $.ajax(
    {
        type: "GET",
        url: service + '/GetAllCountries/',
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

        var trHTML = '';

        $.each(data.Countries, function (i, item) {

            trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
        });

        $('#location').append(trHTML);

        },

        error: function (msg) {

            alert(msg.responseText);
        }
    });
})

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

由于您有两个单独的数组CountriesCities,因此没有统一的项目集合,每个项目都有CountriesCities属性。

同样在修改后的代码中,您尝试在each上使用data.d.results,根据您提供的示例数据,我希望这些item未定义。 总的来说,您可以通过附加单个行来改进代码,但是没有有用的[{City:"LUSAKA",Country:"ZAMBIA"},{City:"HARARE", Country: "ZIMBABWE"}] 具有您需要的两个值。

如果您可以控制JSON数据,可以按如下方式对其进行重组:

$.each(data,function(i,item){
    $("#location tbody").append(
        "<tr>"
            +"<td>"+item.Country+"</td>"
            +"<td>"+item.City+"</td>"
        +"</tr>" )
    })

然后像这样访问:

aggfunc
相关问题