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(),再来看看这个函数:

  url属性,类似于AJAX的跳转url,这里我用了同一个路径下的jsp页面(indexStatisticsAction_getSelect.jsp),下面会再展示;

  data属性,将作为请求的参数,由request获取;

  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>标签回发就可以了。