java中使用$.ajax创建下拉选项

来源:互联网 发布:php删除数组指定元素 编辑:程序博客网 时间:2024/05/21 06:55


从数据库中取出相应数据,存在list中,下面直接从servlet讲:,

  1. servlet

    servlet中,将存储在list中的数据,转为json类型:

    相应代码:

Gsongson =new Gson();//创建Gson对象

StringjsonStr =gson.toJson(list);//list转为json字符串

PrintWriter out = response.getWriter();

out.print(jsStr);//将转化后的字符串,输送到jsp

  1. jsp

  1. 对应的下拉框

<divclass="form-group">

      <labelfor="theid"class="col-sm-2 control-label">主题:</label>

      <divclass="col-sm-6">

<selectclass="form-control"name="theid"id="theid">

</select>

</div>

</div>

 

  1. 对应的ajax代码

$(function(){

      // ajax请求servlet获取主题数据

      $.ajax({

          url:"${pageContext.request.contextPath}/theMe/TheMeServlet?method=findAllTheme",

          type:"POST",

          dataType:"json",

          cache:false,

          async:true,

          success:function(data){

             for(var i = 0;i<data.length;i++){

                 //alert(data[i].);

                  $("#theid").append(" <option id='" + data[i].theid +"'>" + data[i].thename+"</option>");

             }

          }

      })

});

原创粉丝点击