Javabean:
package com.jbben.ajax2;
public class Channel {
private String code;//select中的value值
private String name;//select中显示的项
public Channel() {
}
public Channel(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Servlet代码:
package com.jbben.ajax2;
import com.alibaba.fastjson.JSON;
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("/ChannelServlet")
public class ChannelServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String level = request.getParameter("level");//处理的是一级菜单还是二级菜单
String parent = request.getParameter("parent");//一级菜单的value
List<Channel> list = new ArrayList<>();
if(level.equals("1")){
list.add(new Channel("ai","前沿/区块链/人工智能"));
list.add(new Channel("web","前端/小程序/JS"));
}else if(level.equals("2")){
if(parent.equals("ai")){
list.add(new Channel("micro","微服务"));
list.add(new Channel("blockchain","区块链"));
list.add(new Channel("other","..."));
}else if(parent.equals("web")){
list.add(new Channel("html","HTML"));
list.add(new Channel("css","CSS"));
list.add(new Channel("other","..."));
}
}
String json = JSON.toJSONString(list);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(json);
}
}
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery/jquery-3.3.1.js"></script>
<script src="script/test.js"></script>
<style>
.select{
width: 200px;
font-size: 15px;
height: 30px;
vertical-align: bottom;
}
</style>
</head>
<body>
<select class="select" id="lv1">
<option value="">请选择</option>
</select>
<select class="select" id="lv2"></select>
</body>
</html>
jQuery代码:
//1级菜单的处理
$(function () {
$.ajax({
url:"/testspring2/ChannelServlet",
data:{"level":"1"},
type:"get",
dataType:"json",
success:function (json) {
//console.log(json)
for(let i = 0; i<json.length;i++){
$("#lv1").append("<option value='"+json[i].code+"'>" + json[i].name+"</option>")
}
}
})
})
//2级菜单的处理
$(function () {
$("#lv1").change(function () {
var parent = $(this).val()
//console.log(parent)
$.ajax({
url:"/testspring2/ChannelServlet",
data:{"level":"2","parent":parent},
type:"get",
dataType: "json",
success:function (json) {
console.log(json)
$("#lv2>option").remove()
for(let i = 0;i<json.length;i++){
$("#lv2").append("<option value='"+json[i].code+"'>" + json[i].name+"</option>")
}
}
})
});
})
达到这种效果: