JavaScript之AJAX实现二级联动菜单(jsp+js+servlet
以下是一个简化的示例,展示了如何使用JavaScript和AJAX实现二级联动菜单。
- HTML部分(index.jsp):
<!DOCTYPE html>
<html>
<head>
<title>二级联动菜单</title>
<script src="ajax.js"></script>
<script>
function fetchSubCategories(categoryId) {
var url = 'SubCategoryServlet?categoryId=' + categoryId;
var subCategorySelect = document.getElementById('subCategory');
// 清空二级菜单选项
subCategorySelect.options.length = 0;
// 发送AJAX请求获取子分类
getJSON(url, function(data) {
if (data) {
data.forEach(function(item) {
var option = document.createElement('option');
option.value = item.id;
option.text = item.name;
subCategorySelect.appendChild(option);
});
}
});
}
</script>
</head>
<body>
<form>
<select id="category" onchange="fetchSubCategories(this.value);">
<option value="">选择一级分类</option>
<!-- 动态加载一级分类 -->
</select>
<select id="subCategory">
<option value="">选择子分类</option>
<!-- 动态加载子分类 -->
</select>
</form>
</body>
</html>
- JavaScript部分(ajax.js):
function getJSON(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
}
};
xhr.send();
}
- Servlet部分(SubCategoryServlet.java):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
public class SubCategoryServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int categoryId = Integer.parseInt(request.getParameter("categoryId"));
List<SubCategory> subCategories = fetchSubCategoriesByCategoryId(categoryId);
response.setContentType("application/json");
response.
评论已关闭