
当然了,从界面上完全看不出来一个组件封装的好坏,但至少,你感觉很简洁漂亮,那么好了,有了这层印象,你是否有兴趣继续看下去?我想答案是肯定的。
二、使用方法
①、procity.jsp
首先呢,在页面上加载yunm.combox.js(稍候介绍,至于其他的bootstrap的css和js,不在本章介绍范围内,略过),同时呢,创建两个select,具体格式见如下:
<script type="text/javascript" src="${ctx}/components/yunm/yunm.combox.js"></script><div class="form-group"><div class="row"><div class="col-md-6"><select name="province_code" class="form-control combox" ref="city_select"refUrl="${ctx}/procity?pro_code={value}&city_code=HSLY"></select></div><div class="col-md-6"><select name="city_code" id="city_select" class="form-control"></select></div></div></div><script type="text/javascript"><!--$(function() {if ($.fn.combox) {$("select.combox", $p).combox();}});//--></script>·两个select组件,一个为province_code、一个为city_code。(function($) {var _onchange = function(event) {var $ref = $("#" + event.data.ref);if ($ref.size() == 0)return false;var refUrl = event.data.refUrl;var value = encodeURIComponent(event.data.$this.val());YUNM.debug(value);$.ajax({type : "POST",dataType : "json",url : refUrl.replace("{value}", value),cache : false,data : {},success : function(response) {$ref.empty();addHtml(response, $ref);$ref.trigger("change").combox();},error : YUNM.ajaxError});};var addHtml = function(response, $this) {var json = YUNM.jsonEval(response);if (!json)return;var html = "";$.each(json, function(i) {if (json[i]) {html += "<option value="" + json[i].value + """;if (json[i].selected) {html += " selected="" + json[i].selected;}html += "">" + json[i].name + "</option>";}});$this.html(html);};$.extend($.fn, {combox : function() {return this.each(function(i) {var $this = $(this);var value = $this.val() || "";var ref = $this.attr("ref");var refUrl = $this.attr("refUrl") || "";if (refUrl) {refUrl = refUrl.replace("{value}", encodeURIComponent(value));}if (refUrl) {$.ajax({type : "POST",dataType : "json",url : refUrl,cache : false,data : {},success : function(response) {addHtml(response, $this);if (ref && $this.attr("refUrl")) {$this.unbind("change", _onchange).bind("change", {ref : ref,refUrl : $this.attr("refUrl"),$this : $this,}, _onchange).trigger("change");}},error : YUNM.ajaxError});}});}});})(jQuery);·通过$.extend($.fn, { combox : function() {为jquery增加一个叫combox的底层(可以查询jquery帮助文档)方法。package com.honzh.spring.controller;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.honzh.biz.database.entity.City;import com.honzh.biz.database.entity.Option;import com.honzh.biz.database.entity.Provincial;import com.honzh.common.util.JsonUtil;import com.honzh.spring.service.CityService;import com.honzh.spring.service.ProvincialService;@Controller@RequestMapping(value = "/procity")public class ProcityController extends BaseController {private static Logger logger = Logger.getLogger(ProcityController.class);/** * 当传递city_code,则表明下拉框要被选中,否则不选中 */@RequestMapping("")public void index(@RequestParam(value = "city_code", required = false) String city_code,@RequestParam(value = "pro_code", required = false) String pro_code, HttpServletResponse response) {try {logger.debug("获取所在地区" + city_code + ", 省" + pro_code);// 如果pro_code为””,则表明要获取城市菜单,否则获取市级菜单if (!pro_code.equals("")) {Integer pro_id = ProvincialService.getInstance().getByProvincialcode(pro_code).getId();List<City> citys = CityService.getInstance().getCitysByProvincialId(pro_id);List<Option> coptions = new ArrayList<Option>(citys.size());for (City city : citys) {Option coption = new Option();coption.setId(city.getId());coption.setName(city.getCname());coption.setValue(city.getCode());// 市级菜单被选中if (city_code != null && !city_code.equals("")) {if (city.getCode().equals(city_code)) {coption.setSelected("selected");}}coptions.add(coption);}renderJson(response, coptions);} else {List<Provincial> provincials = ProvincialService.getInstance().getProvincials();// 转换成标准的option属性(name,value,selected)List<Option> options = new ArrayList<Option>(provincials.size());// 被选中的省市// 则说明是展示页面,此时需要为省级菜单和市级菜单设置选择项if (city_code != null && !city_code.equals("")) {Provincial selected_provincial = ProvincialService.getInstance().getProvincialByCitycode(city_code);pro_code = selected_provincial.getProcode();} else {pro_code = provincials.get(0) == null ? "" : provincials.get(0).getProcode();}for (Provincial provincial : provincials) {Option option = new Option();option.setId(provincial.getId());option.setName(provincial.getProname());option.setValue(provincial.getProcode());if (!pro_code.equals("") && provincial.getProcode().equals(pro_code)) {option.setSelected("selected");}options.add(option);}renderJson(response, JsonUtil.toJson(options));}} catch (Exception e) {logger.error(e.getMessage());logger.error(e.getMessage(), e);renderJson(response, null);}}}@RequestParam(value = "city_code", required = false) String city_code,对于RequestParam注解,其实非常好用,这里就不多做解释,只是推广一下,固定个数的参数,用该注解更易于代码的维护。package com.honzh.spring.service;import java.util.ArrayList;import java.util.List;import com.honzh.biz.database.entity.City;import com.honzh.biz.database.entity.Provincial;import com.honzh.biz.database.mapper.ProvincialMapper;import com.honzh.common.spring.SpringContextHolder;public class ProvincialService {private static Object lock = new Object();private static ProvincialService config = null;private ProvincialService() {provincials = new ArrayList<Provincial>();ProvincialMapper mapper = SpringContextHolder.getBean(ProvincialMapper.class);provincials.addAll(mapper.getProvincials());}public static ProvincialService getInstance() {synchronized (lock) {if (null == config) {config = new ProvincialService();}}return (config);}public Provincial getByProvincialcode(String provincial_code) {for (Provincial provincial : provincials) {if (provincial.getProcode().equals(provincial_code)) {return provincial;}}return null;}private List<Provincial> provincials = null;public List<Provincial> getProvincials() {return provincials;}public Provincial getProvincialByCitycode(String city_code) {City city = CityService.getInstance().getCityByCode(city_code);for (Provincial provincial : provincials) {if (provincial.getId().intValue() == city.getProid().intValue()) {return provincial;}}return null;}public Provincial getProvincialByCode(String province_code) {for (Provincial provincial : provincials) {if (provincial.getProcode().equals(province_code)) {return provincial;}}return null;}}⑤、renderJson方法/** * 如果出错的话,response直接返回404 */protected void renderJson(HttpServletResponse response, Object responseObject) {PrintWriter out = null;try {if (responseObject == null) {response.sendError(404);return;}// 将实体对象转换为JSON Object转换String responseStr = JsonUtil.toJson(responseObject);response.setCharacterEncoding("UTF-8");response.setContentType("application/json; charset=utf-8");out = response.getWriter();out.append(responseStr);logger.debug("返回是:" + responseStr);} catch (IOException e) {logger.error(e.getMessage());logger.error(e.getMessage(), e);} finally {if (out != null) {out.close();}}}以上就是本文的全部内容,希望对大家的学习有所帮助。