23.二级联动案例(XML版本)

Controller
@Controller
@RequestMapping("xml")
public class LinkageXMLController {
    /**
     
        湖南
        广东
        湖北
     
     */
    //获取省份
    @RequestMapping("province")
    public void getProvince(HttpServletResponse response) throws Exception {
        response.setContentType("text/xml;charset=utf-8");
        //获取到所有的省份
        StringBuilder sb = new StringBuilder(100);
        sb.append("");
        List list = Province.getAllProvince();
        for (Province obj : list) {
            sb.append("").append(obj.getName())
                    .append("");
        }
        sb.append("");
        response.getWriter().write(sb.toString());
    }

    //获取城市
    @RequestMapping("city")
    public void getCity(Long pId, HttpServletResponse response) throws Exception {
        response.setContentType("text/xml;charset=utf-8");
        //获取到所有的省份
        StringBuilder sb = new StringBuilder(100);
        sb.append("");
        List list = City.getCityByProvinceId(pId);
        for (City obj : list) {
            sb.append("").append(obj.getName())
                    .append("");
        }
        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","/xml/province.do",true);
    
    //监听
    var opHTML = "";
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && ajax.status == 200) {
            var doc = ajax.responseXML;
            var datas = doc.getElementsByTagName("data");
            for(var i = 0;i" +datas[i].innerHTML+"";
            }
            
            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","/xml/city.do?pId="+province.value,true);
        ajax.onreadystatechange = function() {
            
            if (ajax.readyState == 4 && ajax.status == 200) {
                
                var datas = ajax.responseXML;
                var ps = datas.getElementsByTagName("data");
                for(var i = 0;i" +ps[i].innerHTML+"";
                }
                city.innerHTML = opHTML;
            }
        };
        ajax.send();
    };
};

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