通过ajax函数调用返回下拉列表

时间:2017-07-17 02:44:26

标签: javascript java servlets

我正在尝试通过ajax函数调用返回一个arraylist并将结果返回到我的HTML下拉列表。
下面是我的ajax函数,servlet代码和html 我的下拉列表一直空着。不知道哪里出错了。

Servlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Integer p = Integer.parseInt(request.getParameter("studentid"));

    ArrayList<SessionDataBean> result = new ArrayList<>();
    String sessid = null;
    try ( Connection con = JdbcUtil.getConnection()) {
        String sql= "select distinct F.SESSIONID "
                + "from Students F "
                + "where F.studentid = "+p;
        try (Statement st = con.createStatement()) {
            System.out.println(sql);
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()){
                result.add(new SessionDataBean(rs.getString(1)));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        }
    catch (Exception e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    new Gson().toJson(result, response.getWriter()); 

    }

Ajax函数调用代码:

function listSession(){
  var name = document.getElementById("studentid").value;      
  $.ajax({
        url : "<%=context%>/ListSessionsServlet?studentid=" + name,
        type : "POST",
        async : false,
        dataType: "json",
          success : function(data) {
              var toAppend = '';
              $.each(data,function(i,o){
                  toAppend += '<option>'+o.id+'</option>';  <---issue might be here?
                 });

                $('#sessid').append(toAppend);
          }  
    });
 }

HTML code:

    <div class="cell">
        Select Session for Student
        <div class="input-control select mutiple full-size">
            <select id="sessid" name="sessid">
            </select>

        </div>
    </div>

1 个答案:

答案 0 :(得分:1)

服务器需要{/ 1}}参数POST

"studentid"

虽然Integer p = Integer.parseInt(request.getParameter("studentid"));已通过。替代

"name"

代表

url : "<%=context%>/ListSessionsServlet?studentid=" + name