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

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

Mar 31, 2018 am 10:16 AM
ajax load dynamic

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>
Copy after login

二、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);
 }
}
Copy after login

三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>
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Convert VirtualBox fixed disk to dynamic disk and vice versa Convert VirtualBox fixed disk to dynamic disk and vice versa Mar 25, 2024 am 09:36 AM

When creating a virtual machine, you will be asked to select a disk type, you can select fixed disk or dynamic disk. What if you choose fixed disks and later realize you need dynamic disks, or vice versa? Good! You can convert one to the other. In this post, we will see how to convert VirtualBox fixed disk to dynamic disk and vice versa. A dynamic disk is a virtual hard disk that initially has a small size and grows in size as you store data in the virtual machine. Dynamic disks are very efficient at saving storage space because they only take up as much host storage space as needed. However, as disk capacity expands, your computer's performance may be slightly affected. Fixed disks and dynamic disks are commonly used in virtual machines

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

See all articles