jsp+ajax+serverlet实现省市二级联动

jsp界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
function loadProvince() {
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            var data = req.responseText;

            var myObj = eval("(" + data + ")");

            //eval函数:格式化函数--将字符串转化为javascript对象的函数
            for (var i = 0; i < myObj.length; i++) {
                var oneProvince = myObj[i];
                var opKey = oneProvince.split("-")[0];
                var opValue = oneProvince.split("-")[1];

                //找到province对应的下拉框
                var proSelectObj = document.getElementById("proId");

                 var newOption = document.createElement("OPTION");
                 newOption.value = opKey;
                 newOption.innerHTML = opValue;

                 proSelectObj.appendChild(newOption);
            }

            //执行一次加载城市
            loadCity();
        }
    };
    req.open("post", "pa", true);
    req.send(null);
}

function loadCity() {
    var proSelectObj = document.getElementById("proId");

    //获取到当前选中的省份,并用于数据库查询
    var proIdToDB = proSelectObj[proSelectObj.selectedIndex].value;

    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            var data = req.responseText;
            var myObj = eval("(" + data + ")");

            var citySelectObj = document.getElementById("cityId");
            //清理原来的城市信息
            while (citySelectObj.childNodes.length > 0) {
                citySelectObj.removeChild(citySelectObj.lastChild);
            }

            for (var i = 0; i < myObj.length; i++) {
                var oneCity = myObj[i];
                var cityKey = oneCity.split("-")[0];
                var cityValue = oneCity.split("-")[1];

                var newOption = document.createElement("OPTION");
                newOption.value = cityKey;
                newOption.innerHTML = cityValue;

                citySelectObj.appendChild(newOption);
            }
        }
    };
    req.open("post", "ca", true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.send("proId=" + proIdToDB);
}
</script>
</head>
<body onload="loadProvince()">    <!-- 当页面加载完毕时执行 -->

省:
<select id="proId" onchange="loadCity()"> <!-- 选项option变更的时候触发事件 -->
</select>

城市:
<select id="cityId">
</select>
</body>
</html>

serverlet 获取地市数据

package com.shxt.lesson15.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

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

public class ProvinceAjaxServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //加载省份信息
        request.setCharacterEncoding("utf-8");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/lingyun1", "root", "mysql");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from shxt_province");

            ArrayList<String> provinceList = new ArrayList<String>();
            while (rs.next()) {
                String key = rs.getString("PROID");
                String value = rs.getString("PRONAME");
                provinceList.add("\"" + key + "-" + value + "\"");
            }

            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            System.out.println(provinceList);

            out.print(provinceList);

            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Serverlet 根据地市代码获取城市数据

package com.shxt.lesson15.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

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

public class CityAjaxServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        try {
            String proId = request.getParameter("proId");
            String sql = "select * from shxt_city where PROID = ‘" + proId + "‘";
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/lingyun1", "root", "mysql");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            ArrayList<String> cityList = new ArrayList<String>();
            while (rs.next()) {
                String key = rs.getString("CITYID");
                String value = rs.getString("CITYNAME");
                cityList.add("\"" + key + "-" + value + "\"");
            }

            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();

            out.print(cityList);

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

小例子

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<!-- ajax 异步交互(javascript和xml的形式) -->
<script type="text/javascript">
function validData() {

    var value1 = document.getElementById("myText1").value;
    var value2 = document.getElementById("myText2").value;

    //请求对象 request
    var req = new XMLHttpRequest();

    //创建一个监听函数:监视ajax的各个状态:
    //1、open状态:servlet(可以接收参数)
    //2、send发送:发送参数、【重点】需要设置请求头部信息
    //3、reciving反馈:servlet开始向页面发送反馈信息
    //4、loaded载入:servlet发送的信息全部接收完毕
    req.onreadystatechange = function() {
        if (req.readyState == 1) {    //open:准备时间
            var mySpan = document.getElementById("showPosition");
            mySpan.innerHTML = "<img src=‘a.jpg‘ />";
            document.getElementById("myBtn").style.display = "none";
        } else if (req.readyState == 4) {
            var data = req.responseText;
            document.getElementById("myBtn").style.display = "block";
            document.getElementById("showPosition").innerHTML = data;
        }
    };

    //(用post方式)打开myAjax服务应用(Server applet)
    req.open("post", "myAjax", true);

    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //发送
    req.send("a=" + value1 + "&b=" + value2);
}
</script>

</head>
<body>
<input id="myText1" /><br />
<input id="myText2" onblur="validData()" /><span id="showPosition"></span><br />
<input />
<input type="button" id="myBtn" value="提交" />
</body>
</html>

serverlet

package com.shxt.lesson15.servlets;

import java.io.IOException;
import java.io.PrintWriter;

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

public class AjaxServlet extends HttpServlet {

    /**
     * Input/Output    字节流(byte的流)
     * Reader/Writer 字符流(char的流)
     * InputStreamReader ---- 将input转为reader(byte流变char流)
     * */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        try {
            String txt1 = request.getParameter("a");
            String txt2 = request.getParameter("b");

            System.out.println(txt1 + ", " + txt2);

            Thread.sleep(5000);

            //【重点】设置正文类型 -- 页面html
            response.setContentType("text/html; charset=utf-8");

            //servlet向页面发送信息,需要一个response的响应对象
            PrintWriter out = response.getWriter();    //Writer流(字符型输出流---向目标写入信息)

            out.print("返回的信息:发送成功");

            out.flush();    //刷新--流中的数据清空
            out.close();    //流、关闭
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

jsp+ajax+serverlet实现省市二级联动,布布扣,bubuko.com

时间: 2024-10-13 14:14:34

jsp+ajax+serverlet实现省市二级联动的相关文章

JS实现省市二级联动

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF

JavaScript省市二级联动

cities.xml <?xml version="1.0" encoding="GB2312"?> <china> <province name="吉林省"> <city>长春</city> <city>吉林市</city> <city>四平</city> <city>松原</city> <city>通

省市二级联动--使用app-jquery-cityselect.js插件

只有省市二级联动,三级联动还没处理好,会尽快完善. 嵌入id: <div class="form-group"> <label>地址</label> <p>从:</p> <div class="input-group"> <input id="areaIdFrom" name="areaIdFrom" type="hidden"

(转)JavaScript html js 地区二级联动,省市二级联动,省市县js+xml三级联动

JavaScript html js 地区二级联动,省市二级联动,省市县js+xml三级联动 原文链接:http://heisetoufa.iteye.com/blog/353974 比较好的二级联动: 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <HEAD> 4 <TITLE> New Document </TITLE>

JavaScript实现省市二级联动

    JavaScript实现省市二级联动 展示一下效果? 当我鼠标点击前面的省那一栏的时候后面市那一栏会出现相对应的下辖市 实现思路 1. 添加相对应的select容器 2. 然后添加数据 3. 将相应的数据赋值给对应的option控件 方法的讲解 Function()函数 onchange();改变事件 笔者在这里写了一个关于河南与河北的简单联动   省市联动 <body> <select id="province"></select>省 &l

微信小程序picker组件 - 省市二级联动

微信小程序picker组件自带省市区选择器,但是业务需求需要省市选择器,参考官方demo自己写了一个省市选择器 wxml文件 <view class="section"> <view class="section__title">省市二级联动demo</view> <picker mode="multiSelector" bindchange="bindMultiPickerChange&quo

js省市二级联动实例

//动态创建省市二级联动<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><select id="province" onchange="func1(this)"> </sele

jQuery_完成省市二级联动

当填表的时候会让你设计某省某市怎么设计,应该明白,如果你选择了一个确定的省,那么在第二个下拉框内则不会有除了你选择的省的市之外的名称.而这功能用js来实现很麻烦,但是用jq确很容易实现. 原表结构: 代码如下: <!DOCTYPE html> <html> <head> <script typr="text/javascript" src="js/jquery-1.8.3.js"></script> <

JS——省市二级联动

1.核心代码: <script> var cities = new Array(11); cities[0] = new Array("东城区","西城区" ,"崇文区", "宣武区" ,"朝阳区" ,"丰台区","石景山区" ,"海淀区门" ,"头沟区"); cities[1] = new Array(); cit