1. 程式人生 > >Ajax二級聯動

Ajax二級聯動

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: x1c
 4   Date: 2019-12-22
 5   Time: 10:04
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10   <head>
11     <title>$Title$</title>
12     <script>
13       //function裡面的引數如果寫value 則獲取不到
14       function fun1(val){
15           var xhr=  new XMLHttpRequest();
16           xhr.open("GET","phoneServlet?val="+val,true)
17           xhr.onreadystatechange=function () {
18               //只有完成後才顯示
19               if(xhr.readyState==4&&xhr.status==200){
20                   //獲取響應的文字內容
21                   var phone = xhr.responseText;
22                   //包頭不包尾
23                  var phone3= phone.substring(1,phone.length-1)
24 
25                   var phone4 =phone3.split(", ");
26 
27                  var phone2= document.getElementById("p");
28                   //清空原有資料
29                   phone2.innerHTML="<option >-請選擇機型-</option>"
30                  for(var i in phone4){
31                         phone2.innerHTML+="<option>"+phone4[i]+"</option>"
32                   }
33 
34               }
35 
36 
37 
38           }
39           xhr.send(null)
40       }
41 
42     </script>
43   </head>
44   <body>
45 <select onchange="fun1(this.value)">
46   <option >-請選擇手機品牌-</option>
47   <option value="1">華為</option>
48   <option value="2">小米</option>
49   <option value="3">oppo</option>
50 </select>
51   <select id="p">
52     <option >-請選擇機型-</option>
53   </select>
54   </body>
55 </html>

 

package com.bj;

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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/phoneServlet")
public class PhoneServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String value = req.getParameter("val");
        List<String> Phone = new ArrayList<String>();
        if(value.equals("1")){
            Phone.add("HAWEIMATE9 PRO");
            Phone.add("HAWEIMATE10 PRO");
            Phone.add("HAWEIMATE20 PRO");
        } else if("2".equals(value)){
            Phone.add("小米4");
            Phone.add("小米8");
            Phone.add("小米2s");
        } else if("3".equals(value)){
            Phone.add("OPPOX");
            Phone.add("OPPOXx");
            Phone.add("OPPOXxx");
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //集合的輸處格式
        resp.getWriter().print(Phone.toString());
    }
}