本文實(shí)例講述了jQuery實(shí)現(xiàn)動(dòng)態(tài)加載select下拉列表項(xiàng)功能。分享給大家供大家參考,具體如下:
需求說(shuō)明:
以前使用的select下拉列表都是靜態(tài)的,select 的option數(shù)據(jù)都是寫死的。現(xiàn)在項(xiàng)目中的select需要根據(jù)不同的場(chǎng)景使用不同的數(shù)據(jù),解決方式就是動(dòng)態(tài)加載option數(shù)據(jù)。
代碼部分:
下面步驟介紹了如何從數(shù)據(jù)庫(kù)獲取數(shù)據(jù),并動(dòng)態(tài)的在前端顯示。
步驟一:jsp頁(yè)面靜態(tài)的select:
<div> <select id="selectSM"> <option>選擇A</option> <option>選擇B</option> <option>選擇C</option> </select></div>
注意:
1、靜態(tài)的select在某些場(chǎng)景下使用是沒(méi)有問(wèn)題的。但是在產(chǎn)品不同的需求時(shí),動(dòng)態(tài)select更能勝任其多樣性。
2、select有多種寫法,這里是最簡(jiǎn)單的。
步驟二:jQuery通過(guò)ajax請(qǐng)求獲取動(dòng)態(tài)的數(shù)據(jù),并在jsp頁(yè)面顯示。
function IninDepart(){ $("#selectSM").remove();//清空select列表數(shù)據(jù) var state = 1; $.ajax({ type : "POST", url : "<%=basePath%>/getItemDepartList.do", dataType : "JSON", data : {}, success : function(msg) { $("#selectSM").prepend("<option value='0'>請(qǐng)選擇</option>");//添加第一個(gè)option值 for (var i = 0; i < msg.rows.length; i++) { //如果在select中傳遞其他參數(shù),可以在option 的value屬性中添加參數(shù) //$("#selectSM").append("<option value='"+msg.rows[i].id+"'>"+msg.rows[i]+"</option>"); $("#selectSM").append("<option>"+msg.rows[i]+"</option>"); } },error:function(){ alertLayer("獲取數(shù)據(jù)失敗","error"); } });}注意:這里使用的是jQuery、ajax,其他方式也可以實(shí)現(xiàn)。
步驟三:后臺(tái)數(shù)據(jù)的處理。
public JSONObject getItemDepartList(HttpServletRequest request) throws Exception{ //查詢select數(shù)據(jù) List<Map<String, Object>> list = appServices.getAppList(); System.out.println("list::::::::" + list); //獲取數(shù)據(jù)存放到數(shù)組 String[] depart = null; for (Map<String, Object> map : list) { for (String k : map.keySet()) { depart = ((String) map.get(k)).split(","); System.out.println("depart::::::::" + depart); } } //去除數(shù)組中重復(fù)數(shù)據(jù),存放到list List<String> strList = new ArrayList<String>(); for (int i=0; i<depart.length; i++) { if(!strList.contains(depart[i])) { strList.add(depart[i]); } } System.out.println("strList::::::::" + strList); jsonObject.put("rows", strList); return jsonObject;}注意:由于后臺(tái)返回?cái)?shù)據(jù)的問(wèn)題,需要對(duì)數(shù)據(jù)進(jìn)行截取并去除重復(fù)數(shù)據(jù)。如果沒(méi)有這個(gè)需求,可以直接向前端返回一個(gè)數(shù)組或list即可。下面是不同數(shù)據(jù)的控制臺(tái)輸出:
list::::::::[{service_depart=A,B,C,D,E,A,C,D,D,E}]
新聞熱點(diǎn)
疑難解答
圖片精選