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();
        }
    }

}

 

posted @ 2014-08-05 20:24  -琥珀川-  阅读(931)  评论(1编辑  收藏  举报