ajax与json实现省市二级联动

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
   <script language="javascript" src="${pageContext.request.contextPath}/js/xmlHttp.js"></script>  
  <script language="javascript">  
  function submit(){  
   if(document.getElementById('province').options[document.getElementById('province').selectedIndex].value==0){  
    alert("请选择省份");  
    return false;  
   }else{  
     createXmlhttp();
     
        xmlHttp.onreadystatechange= function (){
           if(xmlHttp.readyState==4){  
            if(xmlHttp.status==200){  
             var json=new Object();  
             json=eval("("+xmlHttp.responseText+")");  
             //清空上次的记录  
             while(document.getElementById('city').options.length>0){  
              document.getElementById('city').options.remove(0);  
             }  
             //动态添加数据  
             for(var i=0;i<json.province.length;i++){  
              var o=document.createElement('OPTION');  
              o.text=json.province[i].city;  
              o.value=json.province[i].city;  
              document.getElementById('city').add(o);  
             }  
            }  
           }  
          }
    xmlHttp.open("post","./servlet/ActionServlet",true);  
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");  
       
    xmlHttp.send("province="+document.getElementById('province').options[document.getElementById('province').selectedIndex].value);
    return true;  
   }  
  }  
 
 </script>  
 </head>  
 
 <body>  
  <select name="province" id="province" onchange="return submit()">  
   <option value="0">  
    选择省份  
   </option>  
   <option value="北京">  
    北京
   </option>  
   <option value="河北 ">  
    河北
   </option>  
  </select>  
 
  <select name="city" id="city">  
  </select>  
 
 
 </body>  
</html> 
后台页面

import java.io.IOException;  
import java.io.PrintWriter;  
import java.sql.ResultSet;  
import java.sql.SQLException;    
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import cn.csdn.hr.util.Database;
 
public class ActionServlet extends HttpServlet {  
 
 /**
     * @author lixiansheng
     */
    private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
 
  this.doPost(request, response);  
 }  
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
  System.out.println("dopost");  
  response.setContentType("text/html;charset=utf-8");  
  request.setCharacterEncoding("utf-8");  
  PrintWriter out = response.getWriter();  
  //获取参数  
  String province=request.getParameter("province");  
  System.out.println(province);  
  //查询数据库  
  System.out.println("asdasd");
  Database db=new Database();  
 
  ResultSet rs=db.selectDB(province);  
  //组织JSON字符字面量  
  StringBuffer info=new StringBuffer();  
  //JSON格式开始  
  info.append("{province:[");  
  try {  
   while(rs.next()){  
    System.out.println(rs.getString("city"));  
    info.append("{city:'");  
    info.append(rs.getString("city"));  
    info.append("'},");  
   }  
   //去掉最后那个逗号  
   info.delete(info.length()-1,info.length());  
   //JSON格式结尾  
   info.append("]}");  
   rs.close();  
   db.closeDB();  
  } catch (SQLException e) {  
   e.printStackTrace();  
  }  
  System.out.println(info.toString());  
  //返回JSON给客户端  
  out.print(info.toString());  
  out.flush();  
  out.close();  
 }  

database 数据库连接包
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
 
public class Database {  
 private Connection conn=null;  
 private PreparedStatement pstmt = null;  
 private ResultSet rs = null;  
 private final String URL="jdbc:mysql://localhost:3306/java?user=root&password=1234";  
   
 public Database(){  
  try{  
   Class.forName("com.mysql.jdbc.Driver").newInstance();  
   this.conn=DriverManager.getConnection(this.URL);  
  }catch(Exception e){  
   e.printStackTrace();  
  }  
 }  
   
 public ResultSet selectDB(String province){  
  String sql="select * from address where province=?";  
  try {  
   pstmt = this.conn.prepareStatement(sql);  
   pstmt.setString(1,province);  
   rs = pstmt.executeQuery();  
  } catch (SQLException e) {  
   e.printStackTrace();  
  }  
  return rs;  
 }  
   
 public void closeDB() {  
  try {  
   if (rs != null)  
    rs.close();  
   if (pstmt != null)  
    pstmt.close();  
   if (conn != null)  
    conn.close();  
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
 }  

在数据库中创建province与city即可



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值