Ajax 성 시내 3 급 연결 실현(데 이 터 는 my sql 데이터베이스 에서)

14717 단어 Ajax등급 연결
Ajax 가 성 시내 3 급 연결 을 실현 하려 면 자바 분석 json 기술 이 필요 합 니 다.
전체 데모 다운로드 주 소 는 다음 과 같 습 니 다주문 하 다
address.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

 <script type="text/javascript">

  /** 
   *   XMLHttpRequest   
   */
  function getajaxHttp() {
   var xmlHttp;
   try {
    // Firefox, Opera 8.0+, Safari 
    xmlHttp = new XMLHttpRequest();
   } catch (e) {
    // Internet Explorer 
    try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
     try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (e) {
      alert("        AJAX!");
      return false;
     }
    }
   }
   return xmlHttp;
  }
  /** 
   *   ajax   
   * url--       URL 
   * methodtype(post/get) 
   * con (true(  )|false(  )) 
   * functionName(     ,     ,            ) 
   * (  :        ,    xmlhttp,          ) 
   */
  function ajaxrequest(url, methodtype, con, functionName) {
   //  XMLHTTPRequest  
   var xmlhttp = getajaxHttp();
   //      (          )
   xmlhttp.onreadystatechange = function() {
    //              XMLHTTPRequest    ?
    //       ,XMLHTTPRequest            
    if (xmlhttp.readyState == 4) {
     if (xmlhttp.status == 200) {
      functionName(xmlhttp.responseText);
     }
    }
   };
   //    
   xmlhttp.open(methodtype, url, con);
   //    
   xmlhttp.send();
  }

  window.onload=function(){
   ajaxrequest("addressSerlvet?method=provincial","POST",true,addrResponse);
  }
  //        
  function addrResponse(responseContents){
   var jsonObj = new Function("return" + responseContents)();
   for(var i = 0; i < jsonObj.addrList.length;i++){
    document.getElementById('select').innerHTML += 
     "<option value='"+jsonObj.addrList[i].id+"'>"
      +jsonObj.addrList[i].address+
     "</option>"
   }
  }
  //    
  function pChange(){
   //           
   document.getElementById('selectCity').innerHTML="<option value='-1'>    </option>";
   //        
   document.getElementById('selectArea').innerHTML="<option value='-1'>    </option>";
   //         
   document.getElementById("addr").innerHTML="";
   var val = document.getElementById('select').value;
   if(val == -1){
    document.getElementById('selectCity')[0].selected = true;
    return;
   }
   //       
   ajaxrequest("addressSerlvet?method=city&provincial="+val,"POST",true,cityResponse);
  }
  //        
  function cityResponse(responseContents){
   var jsonObj = new Function("return" + responseContents)();
   for(var i = 0; i < jsonObj.cityList.length;i++){
    document.getElementById('selectCity').innerHTML += 
     "<option value='"+jsonObj.cityList[i].id+"'>"
      +jsonObj.cityList[i].address+
     "</option>"
   }
  }
  //     
  function cChange(){
   var val = document.getElementById('selectCity').value;
   //       
   ajaxrequest("addressSerlvet?method=area&cityId="+val,"POST",true,areaResponse);
  }
  //        
  function areaResponse(responseContents){
   var jsonObj = new Function("return" + responseContents)();
   for(var i = 0; i < jsonObj.areaList.length;i++){
    document.getElementById('selectArea').innerHTML += 
     "<option value='"+jsonObj.areaList[i].id+"'>"
      +jsonObj.areaList[i].address+
     "</option>"
   }
  }
  //      
  function confirM(){
   //       
   var p = document.getElementById("select");
   var pTex = p.options[p.options.selectedIndex].text;
   if(p.value=-1){
    alert("    ");
    return;
   }
   //       
   var city = document.getElementById("selectCity");
   var cityTex = city.options[city.options.selectedIndex].text;
   if(city.value=-1){
    alert("    ");
    return;
   }
   //       
   var area = document.getElementById("selectArea");
   var areaTex = area.options[area.options.selectedIndex].text;
   if(area.value=-1){
    alert("    ");
    return;
   }
   //      id   
   var addr = document.getElementById("addr").value;
   //  
   document.getElementById("show").innerHTML = "        " + pTex + " " + cityTex + " " + areaTex + " " + addr;
  }

 </script>
<body>
 <select id="select" onchange="pChange()">
  <option value="-1">    </option>
 </select>
 <select id="selectCity" onchange="cChange()">
  <option value='-1'>    </option>
 </select>
 <select id="selectArea" onchange="aChange()">
  <option value='-1'>    </option>
 </select>
 <input type="text" id="addr" />
 <button onclick="confirM();">  </button>
 <div id="show"></div>
</body>
</html>

AddressServlet.java

package cn.bestchance.servlet;

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

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

import cn.bestchance.dao.AddressDao;
import cn.bestchance.dao.impl.AddressDaoImpl;
import cn.bestchance.entity.Address;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet("/addressSerlvet")
public class AddressSerlvet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private AddressDao dao = new AddressDaoImpl();

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

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *  response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  response.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  String method=request.getParameter("method");
  if("provincial".equals(method)){
   getProvincial(request, response);
  }
  if("city".equals(method)){
   getCity(request, response);
  }
  if("area".equals(method)){
   getArea(request, response);
  }
 }
 /**
  *    id            
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 protected void getArea(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String cityId = request.getParameter("cityId");
  //            
  ArrayList<Address> areaList = dao.getAreaByCityId(Integer.parseInt(cityId));
  //      json   
  JSONObject jsonObj = new JSONObject();
  JSONArray jsonArray = JSONArray.fromObject(areaList);
  jsonObj.put("areaList", jsonArray);
  String jsonDataStr = jsonObj.toString();

  response.getWriter().print(jsonDataStr);
 }
 /**
  *           
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 protected void getProvincial(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  //            
  ArrayList<Address> addrList = dao.getProvince();
  //      json   
  JSONObject jsonObj = new JSONObject();
  JSONArray jsonArray = JSONArray.fromObject(addrList);
  jsonObj.put("addrList", jsonArray);
  String jsonDataStr = jsonObj.toString();
  response.getWriter().print(jsonDataStr);
 }
 /**
  *          
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 protected void getCity(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String provinceId = request.getParameter("provincial");
  //            
  ArrayList<Address> addrList = dao.getCityByProvinceId(Integer.parseInt(provinceId));

  //      json   
  JSONObject jsonObj = new JSONObject();
  JSONArray jsonArray = JSONArray.fromObject(addrList);
  jsonObj.put("cityList", jsonArray);
  String jsonDataStr = jsonObj.toString();

  response.getWriter().print(jsonDataStr);
 }

}

AddressDao.java

package cn.bestchance.dao;

import java.util.ArrayList;

import cn.bestchance.entity.Address;

public interface AddressDao {
 /**
  *     id   
  * @return
  */
 ArrayList<Address> getProvince();
 /**
  *     id      
  * @param provinceId
  * @return
  */
 ArrayList<Address> getCityByProvinceId(int provinceId);
 /**
  *     id      
  * @param cityId
  * @return
  */
 ArrayList<Address> getAreaByCityId(int cityId);
}

AddressDaoImpl.java

package cn.bestchance.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import cn.bestchance.dao.AddressDao;
import cn.bestchance.entity.Address;
import cn.bestchance.util.DBUtil;

public class AddressDaoImpl implements AddressDao {
 private DBUtil db = new DBUtil();
 @Override
 public ArrayList<Address> getProvince() {
  ArrayList<Address> addrList = new ArrayList<Address>();
  db.openConnection();
  String sql = "select * from province";
  ResultSet rs = db.excuteQuery(sql);
  try {
   while(rs.next()){
    Address addr = new Address();
    addr.setId(rs.getInt(2));
    addr.setAddress(rs.getString(3));
    addrList.add(addr);
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   db.closeResoure();
  }
  return addrList;
 }
 @Override
 public ArrayList<Address> getCityByProvinceId(int provinceId) {
  ArrayList<Address> addrList = new ArrayList<Address>();
  db.openConnection();
  String sql = "select * from city where fatherID = " + provinceId; //431200
  ResultSet rs = db.excuteQuery(sql);
  try {
   while(rs.next()){
    Address addr = new Address();
    addr.setId(rs.getInt(2));
    addr.setAddress(rs.getString(3));
    addrList.add(addr);
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   db.closeResoure();
  }
  return addrList;
 }
 @Override
 public ArrayList<Address> getAreaByCityId(int cityId) {
  ArrayList<Address> addrList = new ArrayList<Address>();
  db.openConnection();
  String sql = "select * from area where fatherID = " + cityId; //431200
  ResultSet rs = db.excuteQuery(sql);
  try {
   while(rs.next()){
    Address addr = new Address();
    addr.setId(rs.getInt(2));
    addr.setAddress(rs.getString(3));
    addrList.add(addr);
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   db.closeResoure();
  }
  return addrList;
 }

}

실체 클래스 Address.java

package cn.bestchance.entity;

public class Address {
 @Override
 public String toString() {
  return "Address [id=" + id + ", address=" + address + "]";
 }
 private int id;
 private String address;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public Address() {
  super();
  // TODO Auto-generated constructor stub
 }
 public Address(int id, String address) {
  super();
  this.id = id;
  this.address = address;
 }

}

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기