The cascade drop-down menu that Bootstrap must learn every day. The bootstrap drop-down menu
This article will introduce the custom bootstrap cascade drop-down menu. The main application scenarios include Provincial/Municipal Association menus. So let's take this example first. Of course, the Association menus in other scenarios are also applicable. To be honest, it takes a lot of effort and time to encapsulate a common component. The so-called universal component should be considered carefully and sighed! This sort of Bootstrap Association select involves many jquery, ajax, springMVC, and other knowledge points!
First, let me make a small introduction on behalf of this custom component.
"Hi, hello, my name is yunm. combox. js. The name that the host gave me is actually quite vulgar. I mainly add two custom attributes to the select component to load the corresponding data. ajax is used for data requests and springMVC is used for backend Data Processing (of course, other methods can also be used, you only need to return the corresponding json data). It is very easy to use!"
I. Interface Effects
Of course, it cannot be seen from the interface that a component package is good or bad, but at least, you feel very simple and beautiful, so well, with this impression, are you interested in continuing to look at it? I think the answer is yes.
Ii. Usage
①. Procity. jsp
First, load yunm on the page. combox. js (for introduction later, css and js of other bootstrap are not covered in this Chapter and skipped). At the same time, create two select statements. The specific format is as follows:
<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>
· Two select components: province_code and city_code.
· Two attributes are added to the provincial menu.
Ref: Specify the association menu as city_select.
RefUrl specifies the URL for the menu to retrieve data
Pro_codeAs a key factor for obtaining Municipal Data
{Value}It is a wildcard. We will continue to talk about the components later.
City_code = HSLYIs used to select the specified provincial/municipal menu, such as the preceding (Henan, Luoyang). If not selected, city_code = is blank
· Class = "combox" adds the jquery selector to the provincial drop-down box
· The key methods for executing the combox component after page loading are described in detail below
②. Yunm. combox. js
Now let's take a look at the key component content!
(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);
· Use $. extend ($. fn, {combox: function () {to add a combox underlying method for jquery (you can query the jquery help documentation.
· Use (function ($) {_ onchange, addHtml}) (jQuery) to create two methods onchange and addHtml for the component during initial page loading. For (function ($) {}) (jQuery); if you don't know anything, hurry up with Baidu!
· Let's first look at the combox method.
Obtain ref and refUrl, and request provincial menu data from the refUrl through ajax. After obtaining the data, use the addHtml method to bind the converted json option to the provincial menu select.
Then, bind the change event to the provincial menu select. The parameters passed are ref (Municipal menu), refUrl (url obtained from municipal data), and $ this (Provincial menu, this allows you to obtain the selected items for the change event, such as Henan)
Use the trigger method to immediately execute the change event to obtain the corresponding municipal menu content.
· Let's take a look at the _ onchange method, which is triggered when you click the provincial menu to obtain the municipal menu list.
RefUrl: the URL requested from the server
Value is used to obtain the selected project of the provincial menu, and then obtain the municipal menu corresponding to the provincial
$ Ref. empty ();Used to clear municipal menus
Use ajax to continue obtaining the municipal menu content and add it to the municipal menu through addHtml.
· AddHtml Method
The jsonEval method is used to perform eval ('+ data +') on the data transmitted from the server. If you do not understand it, you can use Baidu) to process the data. Otherwise, an error occurs.
$. Each (json, function (I) {traverses json, creates an option object through jquery, and then adds it to select.
③ ProcityController
After the front-end introduction, we will go back to the backend for introduction. Of course, you can also ignore this section, because not all associated data is obtained through springMVC, so let's preview the code first!
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. datab Ase. 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);/*** when city_code is passed, it indicates that the drop-down box needs Selected. Otherwise, */@ 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 ("obtain region" + city_code + ", Province" + pro_code); // if pro_code is "", the city menu is to be obtained; otherwise, the city menu 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 (); // convert to the standard option attribute (name, value, selected) List <Option> options = new ArrayList <Option> (provincials. size (); // The selected province/city indicates that the page is displayed. You need to set the option if (ci) for the Provincial and Municipal menus. Ty_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. It is very useful for the RequestParam annotation. I will not explain it more here. It is just a promotion, with a fixed number of parameters, this annotation makes code maintenance easier.
The ProvincialService class and CityService class are two Singleton instances. store the data in the memory as much as possible to reduce the number of queries to the database. I will post an example later.
The Option class encapsulates the key attributes of the front-end option component to facilitate the generalization of the component.
RenderJson (response, JsonUtil. toJson (options); return the data in json format, and paste the detailed code later.
④. ProvincialService. java
Only code examples are provided, without detailed explanation. After all, it is not the focus of this chapter.
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 Method
/*** If an error occurs, response returns the 404 */protected void renderJson (HttpServletResponse response, Object responseObject) {PrintWriter out = null; try {if (responseObject = null) {response. sendError (404); return;} // convert an Object to a JSON Object and convert it to String responseStr = JsonUtil. toJson (responseObject); response. setCharacterEncoding ("UTF-8"); response. setContentType ("application/json; charset = UTF-8"); out = response . GetWriter (); out. append (responseStr); logger. debug ("returned result:" + responseStr);} catch (IOException e) {logger. error (e. getMessage (); logger. error (e. getMessage (), e);} finally {if (out! = Null) {out. close ();}}}
The above is all the content of this article, hoping to help you learn.
Articles you may be interested in:
- Learning the Bootstrap component drop-down menu
- Every day, Bootstrap is a simple entry
- Every day, Bootstrap must learn the grid system (layout)
- Bootstrap daily required drop-down menu
- Navigation bar required by Bootstrap every day
- Two-way binding between custom Angular commands and jQuery-implemented Bootstrap-style data single-choice and multi-choice drop-down boxes
- It is worth sharing the Bootstrap Ace template for menu and Tab page effects.