【JS】【31】读取json文件

前言:

1,json文件和js文件我是放在同一个文件夹下的

2,我的需求是根据json文件中的groupId字段分组,把数据放到对应的标签内

正文:

xx.js

//获取json数据
function getJSON(){  
    $.getJSON("js/basedata.json",function(data){  
        $.each(data,function(infoIndex,info){  
            switch(info["groupId"]){
                case "1":
                    $("#countryList").append("<li><a>"+info["value"]+"</a></li>");
                    break;
                case "2":
                    $("#ageList").append("<li><a>"+info["value"]+"</a></li>");
                    break;
                case "3":
                    $("#contactTimeList").append("<li><a>"+info["value"]+"</a></li>");
                    break;
                case "4":
                    $("#hearSourceList").append("<li><a>"+info["value"]+"</a></li>");
                    break;
            } 
        })      
     })  
}

basedata.json

[
    {"groupId":"1", "name":"country", "value":"Kenya"},
    {"groupId":"1", "name":"country", "value":"Nigeria"},
    {"groupId":"1", "name":"country", "value":"Tanzania"},    
    {"groupId":"1", "name":"country", "value":"Uganda"},
    {"groupId":"1", "name":"country", "value":"Zambia"},
    {"groupId":"1", "name":"country", "value":"Ghana"},    
    {"groupId":"2", "name":"age", "value":"18-24 years"},
    {"groupId":"2", "name":"age", "value":"25-34 years"},
    {"groupId":"2", "name":"age", "value":"35-44 years"},    
    {"groupId":"2", "name":"age", "value":"45-54 years"},
    {"groupId":"2", "name":"age", "value":"55 years"},
    {"groupId":"3", "name":"contactTime", "value":"Eight to Ten"},
    {"groupId":"3", "name":"contactTime", "value":"Ten to Twelve"},
    {"groupId":"3", "name":"contactTime", "value":"Twelve to Two"},    
    {"groupId":"3", "name":"contactTime", "value":"Two to Five"},
    {"groupId":"3", "name":"contactTime", "value":"Five to Eight"},
    {"groupId":"3", "name":"contactTime", "value":"Eight to Ten"},    
    {"groupId":"3", "name":"contactTime", "value":"Anytime"},
    {"groupId":"3", "name":"contactTime", "value":"Weekend"},
    {"groupId":"4", "name":"hearSource", "value":"Referral"},    
    {"groupId":"4", "name":"hearSource", "value":"Advertisement"},
    {"groupId":"4", "name":"hearSource", "value":"Event/Meeting"},    
    {"groupId":"4", "name":"hearSource", "value":"Online Search"},
    {"groupId":"4", "name":"hearSource", "value":"Other"}
]

参考博客:

jQuery中读取json文件 - 雨里去 - CSDN博客
https://blog.csdn.net/abeetle/article/details/8910189

posted @ 2019-07-02 12:03  花生喂龙  阅读(604)  评论(0编辑  收藏  举报