ajax02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>二级联动</title><base href="<%=request.getContextPath()+"/"%>"><script type="text/javascript">var xhr;function change(val) {//发送Ajax的请求//A、创建XHR对象xhr =new XMLHttpRequest();//B、和服务器建立连接xhr.open("get","AjaxServlet2?val="+val,true);//C、执行回调函数xhr.onreadystatechange=process;//D、发送数据xhr.send(null);}function process() {if(xhr.readyState==4&&xhr.status==200){//'[篮球, 足球, 乒乓球]'var text= xhr.responseText;//'篮球, 足球, 乒乓球'var t2= text.substring(1,text.length-1);// ["抖音", " 快手", " YY直播"]var t3= t2.split(",");var s=document.getElementById("s");//每次进入循环需要重置s.innerHTML="<option>--请选择--</option>";for(var i in t3){s.innerHTML+='<option>'+t3[i]+'</option>';}}}</script></head>
<body><select onchange="change(this.value)"><option>--请选择--</option><option value="1">体育</option><option value="2">直播</option><option value="3">美食</option></select><select id="s"><option>--请选择--</option></select></body>
</html>
AjaxServlet2.java
@WebServlet("/AjaxServlet2")
public class AjaxServlet2 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解决响应中文乱码resp.setContentType("text/html;charset=utf-8");//接受数据String val = req.getParameter("val");List<String> list1=new ArrayList<>();list1.add("篮球");list1.add("足球");list1.add("乒乓球");List<String> list2=new ArrayList<>();list2.add("抖音");list2.add("快手");list2.add("YY直播");List<String> list3=new ArrayList<>();list3.add("炒饼");list3.add("炒面");list3.add("抄刀削");Map<String,List<String>> map =new HashMap<>();map.put("1",list1);map.put("2",list2);map.put("3",list3);//用户响应的集合List<String> list = map.get(val);resp.getWriter().print(list);}
}