24.二级联动案例(JSON版本)

Controller
@Controller
@RequestMapping("json")
public class LinkageJSONController {
    /**
     [
        {id:1,name="湖南"},
        {id:2,name="广东"},
        {id:3,name="湖北"}
     ]
     */
    //获取省份
    @RequestMapping("province")
    public void getProvince(HttpServletResponse response) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        //获取到所有的省份
        StringBuilder sb = new StringBuilder(100);
        sb.append("[");
        List list = Province.getAllProvince();
        for (Province province : list) {
            sb.append("{id:").append(province.getId()).append(",name:\"").append(province.getName())
                    .append("\"},");
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append("]");
        response.getWriter().write(sb.toString());
    }

    //获取城市
    @RequestMapping("city")
    public void getCity(Long pId, HttpServletResponse response) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        //获取到所有的省份
        StringBuilder sb = new StringBuilder(100);
        sb.append("[");
        List list = City.getCityByProvinceId(pId);
        for (City obj : list) {
            sb.append("{id:").append(obj.getId()).append(",name:\"").append(obj.getName())
                    .append("\"},");
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append("]");
        response.getWriter().write(sb.toString());
    }
}
HTML

    
    
    

JS
window.onload = function() {
    
    //获取到省份的选择器
    var province = document.getElementById("provinces");
    console.log(province);
    //发送省份的请求
    
    //创建ajax对象
    var ajax = new XMLHttpRequest();
    
    //open
    ajax.open("get","/json3/province.do",true);
    
    //监听
    var opHTML = "";
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && ajax.status == 200) {
            var datas = eval("(" + ajax.responseText + ")");
            for(var i = 0;i" +datas[i].name+"";
            }
            
            province.innerHTML += opHTML;
        }
    };
    ajax.send();
    
    province.onchange = function() {
        var city = document.getElementById("cities");
        var opHTML = "";
        
        //优化,如果省选的是请选择,就没必要发送请求了
        if (province.value < 0) {
            city.innerHTML = opHTML;
            return;
        }
        
        ajax.open("get","/json3/city.do?pId="+province.value,true);
        ajax.onreadystatechange = function() {
            
            if (ajax.readyState == 4 && ajax.status == 200) {
                var datas = eval("(" + ajax.responseText + ")");
                for(var i = 0;i" +datas[i].name+"";
                }
                city.innerHTML = opHTML;
            }
        };
        ajax.send();
    };
};

你可能感兴趣的:(24.二级联动案例(JSON版本))