如何利用Ajax实现地区三级联动详解(2)

$("#city").on("change", function(){ let code = $(this).find(":selected").val(); $.post("village",{"code":code}, function(data){ $("#village").empty(); $("#village").append("<option>---县---</option>"); $.each(data, function(){ $("#village").append("<option value="+this.code+">"+this.name+"</option>"); }) },"json");

代码雷同以至于VillageController.class也是雷同,加了一些判断而已多了一个循环,

package com.daben.controller; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; 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 com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @WebServlet("/village") public class VillageController extends HttpServlet{ private static final long serialVersionUID = -6513954606070061277L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("appliaction/json;charset=utf-8"); String code = req.getParameter("code"); String cityCode = (String)req.getSession().getAttribute("cityCode"); ObjectMapper om = new ObjectMapper(); String path = req.getServletContext().getRealPath("/WEB-INF/classes/city_code.json"); FileInputStream fi = new FileInputStream(path); List<Map<String, Object>> province = om.readValue(fi, new TypeReference<List<Map<String,Object>>>() {}); List<Map<String,Object>> list = new ArrayList<>(); Iterator<Map<String, Object>> iterator = province.iterator(); while(iterator.hasNext()) { Map<String, Object> map2 = iterator.next(); if(map2.get("code").equals(cityCode)) { map2.remove("code"); map2.remove("name"); list=(List<Map<String,Object>>) map2.get("city"); break; } } List<Map<String,Object>> list1 = new ArrayList<>(); Iterator<Map<String,Object>> iterator2 = list.iterator(); while(iterator2.hasNext()) { Map<String,Object> next = iterator2.next(); if(next.get("code").equals(code)) { next.remove("code"); next.remove("name"); list1 = (List<Map<String,Object>>)next.get("area"); } } om.writeValue(resp.getWriter(), list1); } }

完结:只提供了代码,但是为什么这样何不自己去想一想?

json地区文件下载:

关注公众号 “程序员零距离” 回复 “201231” 即可下载

如何利用Ajax实现地区三级联动详解

↑关注上方公众号回复 “201231” 即可下载↑

思考?可不可以用xml文件来代替json文件?将jackson换成jsoup来解析?

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wszpzf.html