1. 程式人生 > >jquery實現動態載入select下拉框

jquery實現動態載入select下拉框

如題,直接上程式碼,實戰學習。

<head><title>jquery實現動態載入select下拉選項</title> 
<script type="text/javascript">
function init(){
  makemoduleSelect();
 }
 //載入模板下拉框選項
 function makemoduleSelect(){
  $.ajax({
   url : 'indexStatisticsAction_getSelect.jsp',
   data: { page:'clientindexStatistics.jsp',method:'get_modtitlecode'},
   success : function(result){
    $("#makemodule").append(result);
   }
  });
 }</script>
</head>  
<body onload="init()">
下拉框<select name="makemodule" id="makemodule" style='width:130px' onchange='makemoduleSelected()'>
   <option> ------- </option>
</select></body>

以上html被載入時,由於body標籤裡面設定了onload屬性,則其對應的javascript函式會執行,最後到 function makemoduleSelect(),再來看看這個函式:

  1. url屬性,類似於AJAX的跳轉url,這裡我用了同一個路徑下的jsp頁面(indexStatisticsAction_getSelect.jsp),下面會再展示;
  2. data屬性,將作為請求的引數,由request獲取;
  3. success屬性,表示該jquery的ajax請求成功返回後將執行的程式碼,這裡的$("#makemodule")指的是下拉框。

下面是ajax請求的url所對應的jsp,這裡刪掉了JDBC相關的包,自行引入嘛,JDBC的就不多說了,根據需要把業務邏輯碼出來吧。

<%@ page import="java.util.*"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.io.PrintWriter"%>
<%
	String userId = (String) session.getAttribute("userid");
	String method = request.getParameter("method");
	String fromPage = request.getParameter("page");
	String sql1 = "select modtitlename,modtitlecode from makemodule where userid = '?userId?' and modulename_en='?modulename_en?' group by modtitlename "; 
	System.out.println("---getting select_option from:"+fromPage+"----" + new Date());
	
	//獲取模板選項	
	if(method.equals("get_modtitlecode")){
		String sql = sql1.replace("?userId?",userId);
		if(fromPage.equals("acindexStatistics.jsp")){
			sql = sql.replace("?modulename_en?","acsta");
		}else if(fromPage.equals("apindexStatistics.jsp")){
			sql = sql.replace("?modulename_en?","apsta");
		}else if(fromPage.equals("clientindexStatistics.jsp")){
			sql = sql.replace("?modulename_en?","terminalsta");
		}
		System.out.println(sql);
		StringBuffer rsOption = new StringBuffer();
		Db db = new Db();
		try {
			db.prepareQuery();
			ResultSet rs = db.executeQuery(sql);
			while (rs!=null && rs.next()) {
				rsOption.append("<option value='"+rs.getString("modtitlecode")+"'>"+StringOperator.ISO2GB(rs.getString("modtitlename"))+"</option>");
			}
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endQuery();
		}
		PrintWriter pout = response.getWriter();
		pout.write(rsOption.toString());
		pout.flush();
		pout.close();
	}
%>


上面的sql語句將取出兩個值,分別為select下拉框的顯示值和真值,套個<option>標籤回發就可以了。