Home  >  Article  >  Web Front-end  >  How to dynamically load combo boxes with Ajax (code attached)

How to dynamically load combo boxes with Ajax (code attached)

php中世界最好的语言
php中世界最好的语言Original
2018-03-31 10:16:241344browse

This time I will show you how to dynamically load a combo box with Ajax (with code). What are the precautions for Ajax to dynamically load a combo box? The following is a practical case, let's take a look.

一 province.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 <html>
  <head>
   <script type="text/javascript" language="javaScript">
    var xmlHttp = false; //全局变量,用于记录XMLHttpRequest对象
    function createXMLHttpRequest() {
     if(window.ActiveXObject) { //Internet Explorer时,创建XMLHttpRequest对象的方法
      try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch(e) {
      try {       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       //旧版本的Internet Explorer,创建XMLHttpRequest对象
      } catch(e) {
       window.alert("创建XMLHttpRequest对象错误"+e);
      } 
     }
    } else if(window.XMLHttpRequest) { //mozilla时,创建XMLHttpRequest对象的方法
      xmlHttp = new XMLHttpRequest();
     } 
    if(!(xmlHttp)) { //未成功创建XMLHttpRequest对象
      window.alert("创建XMLHttpRequest对象异常!");
    } 
    }
   //下拉列表项改变时的操作
   function proChange(objVal) {
     createXMLHttpRequest(); //创建XMLHttpRequest对象
     document.getElementById("city").length = 1;   //根据ID获取指定元素,并赋值
     xmlHttp.onreadystatechange = cityList; //指定onreadystatechange处理函数
     var url="CityByXMLServlet?province="+objVal; //请求的URL地址
     xmlHttp.open("POST",url,true);
     xmlHttp.send(null);
    }
    function cityList() { //onreadystatechange的处理函数
    if(xmlHttp.readyState==4) {
      if(xmlHttp.status==200) {
       parseXML(xmlHttp.responseXML);   //解析服务器返回的XML数据
     }
     }
   }
    //解析xml信息,以添加地市
    function parseXML(xmlDoc) {
    var len = xmlDoc.getElementsByTagName("city");
    //获取XML数据中所有的“city”元素对象集合
     var _citySel = document.getElementById("city");   //根据ID获取页面中的select元素
     for(var i=0;i<len.length;i++) { //遍历XML数据并给select元素添加选项
     var opt = document.createElement("OPTION");   //创建option对象
     opt.text = xmlDoc.getElementsByTagName("city")[i].firstChild.data;
     //指定新创建元素的text属性值
     opt.value = xmlDoc.getElementsByTagName("city")[i].firstChild.data;
    //指定新创建元素的value属性值
     _citySel.add(opt); //为select元素添加option
    }
    }
   </script>
   <title>动态加载组合框</title>
  </head>
  <body>
   <table align="center" border=1 width="320">
    <tr>
     <td>省份:</td>
    <td>
     <select id="province" onChange="proChange(this.value);" style="width:85">
      <option value="gd">广东</option>
       <option value="gx">广西</option>
       <option value="hn">湖南</option>
      <option value="hb">湖北</option>
      <option value="ah">安徽</option>
     </select>
    </td>
    </tr>
   <tr>
    <td>城市:</td>
    <td>
     <select id="city" style="width:85">
       <option value="">--请选择--</option>
     </select>
    </td>
    </tr>
   </table>
 </body>
 </html>

二、CityByXMLServlet.java

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class CityByXMLServlet
 */
@WebServlet("/CityByXMLServlet")
public class CityByXMLServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
  private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";
  /**
   * @see HttpServlet#HttpServlet()
   */
  public CityByXMLServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
 /**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      response.setContentType(CONTENT_TYPE); //设置服务器响应类型
       String province =request.getParameter("province");
       StringBuffer city = new StringBuffer("<citys>"); //记录返回XML串的对象
       if("gx".equals(province)){
       List list=cityInit(); //获取城市列表
        for(int i=0;i<list.size();i++){
           city.append("<city>"+list.get(i)+"</city>");
        }      
       }else if("hn".equals(province)){
       List list = cityInit1(); //获取城市列表
       for(int j=0;j<list.size();j++){
           city.append("<city>"+list.get(j)+"</city>");
       }
        }else if("hb".equals(province)){
        List list = cityInit2(); //获取城市列表
        for(int j=0;j<list.size();j++){
           city.append("<city>"+list.get(j)+"</city>");
        } 
       }
      city.append("</citys>");
      PrintWriter out = response.getWriter();
      out.println(city.toString());
      out.flush(); //输出流刷新
      out.close(); //关闭输出流
     }
     /*
     * 初始化城市
     */
  public List<String> cityInit2() {
    List<String> cityList = new ArrayList<String>();
   //添加城市列表
    cityList.add("武汉");
    cityList.add("襄阳");
    cityList.add("黄冈");
    cityList.add("荆门");
    cityList.add("十堰");
    cityList.add("黄石");
    return cityList;
  }
     public List<String> cityInit(){
       List<String> cityList = new ArrayList<String>();
     //添加城市列表
       cityList.add("南宁");
       cityList.add("桂林");
       cityList.add("北海");
       cityList.add("河池");
       cityList.add("梧州");
       cityList.add("玉林");
    return cityList;
   }
    public List<String> cityInit1() {
    List<String> cityList = new ArrayList<String>();
   //添加城市列表
    cityList.add("长沙");
    cityList.add("湘潭");
    cityList.add("岳阳");
    cityList.add("常德");
    cityList.add("衡阳");
    cityList.add("邵阳");
    return cityList;
  }
    /**
     *当前Servelt的初始化方法. <br>
     *
     * @throws ServletException发生ServletExceptio时抛出
     */
    public void init() throws ServletException {
    }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doGet(request, response);
 }
}

三web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.4">
<servlet>
  <servlet-name>CityByXMLServlet</servlet-name>
  <servlet-class>servlet.CityByXMLServlet</servlet-class><!--类的位置 -->
</servlet>
<servlet-mapping>
  <servlet-name>CityByXMLServlet</servlet-name><!--你创建的类名 -->
  <url-pattern>/CityByXMLServlet</url-pattern>
</servlet-mapping>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Asynchronous implementation of ajax file upload form

Asynchronous implementation of ajax file download

The above is the detailed content of How to dynamically load combo boxes with Ajax (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn