当前位置: 代码迷 >> JavaScript >> 利用JSON实现Ajax动态加载上拉列表框
  详细解决方案

利用JSON实现Ajax动态加载上拉列表框

热度:143   发布时间:2012-10-06 17:34:01.0
利用JSON实现Ajax动态加载下拉列表框
①客户端利用XMLHttpRequest对象异步传递参数到服务器

②服务端接收参数并查询数据库,根据结果集组织JSON数据,然后返回JSON

③客户端获取服务器响应后,立即执行回调函数,解析JSON数据,然后加载到页面上

示例:
xmlhttp.js文件
var xmlHttp=false;
function createXMLHttpRequest(){
	if(window.ActiveXObject){
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(ee){
				xmlHttp=false;
			}
		}
	}else if(window.XMLHttpRequest){
		try{
			xmlHttp=new XMLHttpRequest();
		}catch(e){
			xmlHttp=false;
		}
	}
}
①前端页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <script language="javascript" src="js/xmlhttp.js"></script>
  <script language="javascript">
  function submit(){
   if(document.getElementById('province').options[document.getElementById('province').selectedIndex].value==0){
    alert("请选择省份");
    return false;
   }else{
    createXMLHttpRequest();
    xmlHttp.onreadystatechange=callback;
    xmlHttp.open("post","/Ajax/ActionServlet");
    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;
   }
  }
  function callback(){
   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);
     }
    }
   }
  }
 </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>

②服务器端处理

package com.hzp.servlet;

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 com.hzp.util.Database;

public class ActionServlet extends HttpServlet {

 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);
  //查询数据库
  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();
 }
}
③数据库操作封装

package com.hzp.util;

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/ajax?user=root&password=515422";
 
 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();
  }
 }
}

?

  相关解决方案