使用Json实现省市二级联动

1。导包:
xpp3_min-1.1.4c.jar和xstream-1.3.1.jar
2。06provinceCity.html文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>省市二级联动:返回的是XML</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    <script type="text/javascript" src="util.js"></script>
    <script type="text/javascript">
        /*
        <provinces>
          <province name="北京" description="首都">
            <city name="海淀区" description="没啥可描述的"/>
            <city name="朝阳区" description="没啥可描述的"/>
            <city name="昌平区" description="没啥可描述的"/>
          </province>
          <province name="山东" description="SD省份">
            <city name="济南市" description="泉城省会"/>
            <city name="青岛市" description="没啥可描述的"/>
            <city name="淄博市" description="没啥可描述的"/>
          </province>
          <province name="湖北" description="九头鸟省份">
            <city name="武汉市" description="省会"/>
            <city name="荆州市" description="没啥可描述的"/>
            <city name="襄阳市" description="没啥可描述的"/>
          </province>
        </provinces>
        */
        var doc;
        window.onload=function(){

            var xhr = getXmlHttpRequest();

            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        //显示省份下拉列表
                        doc = xhr.responseXML;//返回Document对象

                        //解析XML,初始化省份列表
                            var xmlProvinces = doc.getElementsByTagName("province");
                            //得到xml中的所有province元素的name属性
                            for(var i=0;i<xmlProvinces.length;i++){
                                var provinceName = xmlProvinces[i].getAttribute("name");
                                //遍历:HTML DOM给id为province添加option子元素
                                var htmlOption = new Option(provinceName,provinceName);
                                document.getElementById("province").add(htmlOption);
                            }

                    }
                }
            }
            xhr.open("GET","/Json_project/servlet/ServletDemo?time="+new Date().getTime());
            xhr.send(null);
        }
        function selectCity(provinceObj){
            document.getElementById("city").length=1;
            var selectedProvinceName = provinceObj.value;//用户选择的省份
            var xmlProvinces = doc.getElementsByTagName("province");
            for(var i=0;i<xmlProvinces.length;i++){
                var provinceName = xmlProvinces[i].getAttribute("name");
                if(selectedProvinceName==provinceName){
                    //找他的所有城市的name
                    var xmlCitys = xmlProvinces[i].getElementsByTagName("city");
                    for(var j=0;j<xmlCitys.length;j++){
                        var htmlOption = new Option(xmlCitys[j].getAttribute("name"),xmlCitys[j].getAttribute("name"));
                        document.getElementById("city").add(htmlOption);
                    }
                }
            }
        }
    </script>
  </head>

  <body>
    <select id="province" name="province" onchange="selectCity(this)"></select>
    <select id="city" name="city">
        <option value="">请选择</option>
    </select>
  </body>
</html>

3。ServletDemo.java文件:

package com.itheima.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.domain.City;
import com.itheima.domain.Province;
import com.thoughtworks.xstream.XStream;
//返回xml
public class ServletDemo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Province> provinces = new ArrayList<Province>();

        Province bj = new Province("北京", "首都");
        bj.getCitys().add(new City("海淀区", "没啥可描述的"));
        bj.getCitys().add(new City("朝阳区", "没啥可描述的"));
        bj.getCitys().add(new City("昌平区", "没啥可描述的"));

        Province sd = new Province("山东", "SD省份");
        sd.getCitys().add(new City("济南市", "泉城省会"));
        sd.getCitys().add(new City("青岛市", "没啥可描述的"));
        sd.getCitys().add(new City("淄博市", "没啥可描述的"));

        Province hb = new Province("湖北", "九头鸟省份");
        hb.getCitys().add(new City("武汉市", "省会"));
        hb.getCitys().add(new City("荆州市", "没啥可描述的"));
        hb.getCitys().add(new City("襄阳市", "没啥可描述的"));

        provinces.add(bj);
        provinces.add(sd);
        provinces.add(hb);

        XStream xt = new XStream();

        //设置别名:对象对应的标签的名称
        xt.alias("provinces", List.class);
//      xt.alias("province", Province.class);
//      xt.alias("city", City.class);
        xt.autodetectAnnotations(true);
        String xml = xt.toXML(provinces);
        //System.out.println(xml);
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(xml);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

4。Province.java文件:

package com.itheima.domain;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

//ʡ��
@XStreamAlias("province")
public class Province {
    @XStreamAsAttribute
    private String name;
    @XStreamAsAttribute
    private String description;
    @XStreamImplicit(itemFieldName="city")
    private List<City> citys = new ArrayList<City>();


    public Province(){}

    public Province(String name, String description) {
        super();
        this.name = name;
        this.description = description;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public List<City> getCitys() {
        return citys;
    }

    public void setCitys(List<City> citys) {
        this.citys = citys;
    }

}

5。City.java文件:

package com.itheima.domain;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

@XStreamAlias("city")
public class City {
    @XStreamAsAttribute
    private String name;
    @XStreamAsAttribute
    private String description;

    public City(){}


    public City(String name, String description) {
        super();
        this.name = name;
        this.description = description;
    }


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

6。util.js文件:

function getXmlHttpRequest() {
    var xhr;

    try {
        // Firefox, Opera 8.0+, Safari
        xhr = new XMLHttpRequest();
    } catch (e) {

        // Internet Explorer
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("您的浏览器不支持AJAX!");
                return false;
            }
        }
    }
    return xhr;
}

7。web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <servlet-name>ServletDemo</servlet-name>
    <servlet-class>com.itheima.servlet.ServletDemo</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/servlet/ServletDemo</url-pattern>
  </servlet-mapping>

</web-app>

8。运行:http://localhost:8080/Json_project/06provinceCity.html
结果:这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值