ajax入門-實現省份下拉框

ajax請求步驟

  1. 獲取xmlHttpRequest對象
  2. 設置回調函數(onreadystate用來綁定回調函數)
  3. 設置發送參數
  4. 向服務器發送請求

ajax實現省份聯動

  工具類CityUtils

  

package utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ztr
 * @version 建立時間:2021年5月13日 下午7:40:29
 * 類說明
 */
public class CityUtils {
    private static final Map<String, String> citys = new HashMap<String, String>();
    static{
        citys.put("黑龍江", "哈爾濱,大慶,齊齊哈爾");
        citys.put("江西","南昌,九江,贛州");
        citys.put("遼寧", "瀋陽,大連,葫蘆島");
    }
    //獲取省份方法
    public static String getProvince(){
        //獲取map中的鍵
        Set<String> set = citys.keySet();
        String provinceString = "";
        for(String p :set){
            provinceString += p + ",";
        }
        //爲了取出字符串尾部的逗號
        return provinceString.substring(0,provinceString.length()-1);
    }
    //獲取城市信息
    public static String getCity(String provincename){
        //獲取map中指定的鍵所對應的值
        return citys.get(provincename);
    }
}

  ProvinceServlet.javajavascript

  

package servlet;

import java.io.IOException;

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

import utils.CityUtils;

/**
 * Servlet implementation class ProvinceServlet
 */
public class ProvinceServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲得省份信息
        String province = CityUtils.getProvince();
        System.out.println(province);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/text");
        response.getWriter().write(province);
    }

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

}

  CitysServlet.javahtml

  

package servlet;

import java.io.IOException;

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

import utils.CityUtils;

/**
 * Servlet implementation class CityServlet
 */
public class CityServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //獲得省份信息
        String pname = request.getParameter("pname");
        //根據省份名稱獲得對應的城市信息
        String city = CityUtils.getCity(pname);
        //寫回到瀏覽器信息
        //設置響應編碼
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/text");
        response.getWriter().write(city);
        
    }

  demo3.htmljava

  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/my.js"></script>
<script type="text/javascript">
//獲取省份信息
    function getProvince() {
        //向服務器中發送請求獲取省份信息
        //1獲取XMLHttpRequest對象
        var xmlHttp = getXMLHttprequest();
        //2綁定回調函數對服務器響應的數據進行處理
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState == 4){
                if(xmlHttp.status == 200){
                    //將服務器獲得的信息吃力填充到省份下拉框中
                    //獲取服務器響應的數據
                    var provinces = xmlHttp.responseText;
                    var ps = provinces.split(",");
                    //使用html dom來完成將數據填充到下拉框操做
                    for(var i = 0; i< ps.length;i++){
                        var option = document.createElement("option");
                        option.text = ps[i];
                        //將option添加到下拉框中
                        document.getElementById("province").add(option);
                    }
                }
            }
        }
        //3設置發送請求的方法和url
        xmlHttp.open("POST","http://localhost:8080/ajax/ProvinceServlet");
        //4發送請求
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttp.send("null");
    }
    //獲取城市信息
    function getCity() {
        //獲取省份名稱
        var provinceElement = document.getElementById("province");
        var ops = provinceElement.options;
        //selectedIndex是返回已經被選中的下拉框
        var option = ops[provinceElement.selectedIndex]
        //獲取被選中的省份
        var pname = option.text;
        //獲取XMlHttpRequest對象
        var xmlHttp = getXMLHttprequest();
        //綁定回調事件,對服務器響應的數據進行處理
        xmlHttp.onreadystatechange = function() {
            if(xmlHttp.readyState == 4){
                if(xmlHttp.status == 200){
                    document.getElementById("city").innerHTML = "<option>--請選擇城市--</option>";
                    var citys = xmlHttp.responseText;
                    //split將字符串分割爲字符串數組
                    var cs = citys.split(",");
                    //使用html dom 來完成將數據填充到下拉框操做
                    for (var i= 0;i < cs.length; i++) {
                        //新建一個新標籤
                        var option = document.createElement("option");
                        option.text = cs[i];
                        //將option加入下拉框中
                        document.getElementById("city").add(option);
                    }
                }
            }    
        }
        //設置發送的請求的方式和url
        var url = "http://localhost:8080/ajax/CityServlet";
        xmlHttp.open("POST",url);
        //發送請求
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttp.send("pname="+pname);
    }
</script>
</head>
<!-- 當頁面加載完成以後加載省份 -->
<body onload="getProvince()">
<!--  onchange事件,當咱們選中某一個省份時-->
    <select id="province" onchange="getCity()">
        <option>--請選擇省份--</option>
    </select>
    <select id="city">
        <option>--請選擇城市--</option>
    </select>
</body>
</html>
相關文章
相關標籤/搜索