使用JQuery用JSON.NET动态编写手风琴菜单

时间:2014-03-05 13:57:55

标签: jquery html json json.net accordion

我用HTML / jQuery写了一个手风琴菜单。我使用JSON动态地将信息加载到手风琴中。问题是我的原始JSON是以特定格式编写的 - 我理解并知道如何通过jQuery访问的格式。

我开始使用JSON.NET将我的数据序列化为JSON对象(简单有效)。举个例子:

以前的JSON格式(这是硬编码的):

{
    "Country": [
        {
            "CountryName": "exampleCountry",
            "Region": [
                {
                    "RegionName": "exampleRegion",
                    "SubRegion": [
                        {
                            "SubRegionName": "exampleSubRegion"
                        }
                    ]
                }
            ]
        }
    ]
}

JSON.NET输出格式(从数据库中检索):

[
  {
    "Country": "exampleCountry",
    "Region": "exampleRegion",
    "SubRegion": "exampleRegion"
  }
]

我的手风琴应该看起来像:

---Country---
    ---exampleCountry1---
        ---exampleRegion1---
        ---exampleRegion2---
        ---exampleRegion3---
            ---exampleSubRegion1---
            ---exampleSubRegion2---
            ---exampleSubRegion3---
    ---exampleCountry2---
    ---exampleCountry3---

这是我用来返回原始JSON文件中的值的jQuery:

$.getJSON('example.json', function (cwData) {
    $.each(cwData.Country, function (i, country) { // loop through all the countries
        var countries = '<li class="country_name"><a href="#">' + country.CountryName + '</a></li>'; // the name of the country
        var country_region = '<ul class="country_region">'; // create a list of all the regions in the country

        $.each(Country.Region, function (i, region) { // loop through all the regions
            country_region += '<li class="region_name"><a href="#">' + region.RegionName + '</a></li>'; // the name of the region
            var region_subregion = '<ul class="region_subregion">'; // create a list of all the subregions in the region

            $.each(Region.SubRegion, function (i, subregion) { // loop through all the regions
                region_subregion += '<li class="subregion_name"><a href="#">' + subregion.SubRegionName + '</a></li>'; // the name of the subregion
            });
            region_subregion += '</u>'; //close the list tags
            $(region_subregion).appendTo(country_region); // append the subregion to the region
        });
        country_region += '</ul>'; //close the list tags
        $(countries).appendTo('#accordion_menu').append(country_region); // append the region to the country and append the country to the accorion menu
    });
});

我添加了尽可能多的评论,以使内容更具可读性/可理解性。 正如您可能已经注意到的那样 - 之前的JSON具有更多的“层次结构” - 结构,而不是具有更多“平面”结构的新JSON。

是否可以使用jQuery 访问和操作 JSON.NET来动态构建手风琴?如果是这样,我该怎么做?解决方案是否可以改变我将数据存储到序列化对象的方式?

1 个答案:

答案 0 :(得分:0)

当然,可以使用客户端的AJAX调用从服务器获取手风琴的各个部分,然后动态更新UI。但要做到这一点,你几乎必须改变你的代码现在如何工作的一切:

  • 您必须编写服务器端API以便只检索您想要的部分;
  • 您可能需要更改数据库查询才能使用API​​;
  • 当用户点击手风琴时,您必须更改UI / jQuery代码以进行调用。
  • 如果预先拥有所有数据,用户界面的响应速度将会降低。

由于您的UI代码已经使用了分层结构,我认为更好的解决方案是让您的服务器将平面子区域列表转换为UI期望的分层格式。