如何在下拉选择框的更改事件中使用Ajax和jQuery调用servlet?

时间:2013-01-09 12:14:19

标签: jquery ajax jsp servlets

我正在研究JSP和Servlet中的分页代码。在这里我想显示员工的名单。我尝试使用MVC Pattern设计它。

调用以下代码的步骤:

  1. 在浏览器中调用dispEmployee.jsp页面。
  2. 点击列表中的超链接。其中调用EmpServlet.java servlet。
  3. 从选择框中选择页码以在页面之间导航。
  4. 问题:

    这里当我们按照上面提到的步骤去。到第二步,一切都运行良好。 当我们尝试调用step3时,即当我们从选择框中选择另一个页码时,它会为所选页面提供信息,但之后每当我们从选择框中选择另一个页面时,都不会调用更改事件

    请告诉我朋友我的ajax和jQuery代码有什么问题。

    请参阅以下代码。 这里没有给出DAO和Bean代码。

    dispEmployee.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Employees</title>
    <script type="text/javascript" src="js/stdlib/jquery-1-4-2.js"></script>
    <script type="text/javascript">
     $(document).ready(function(){
    alert("this is test");
    // var link= $('#id_pageselect');
    var selpage=$('#id_pageselect').val();
    $("#id_pageselect").change(function(){
        alert("this is test1"); 
    /*  $.ajax({
         type:"Post",
         url:"/EmpServletSnipet",
         data:"page=" + selpage,
         success:function(content){
                    alert("test2"); 
                    $('#display').empty();
                    $('#display').append(content);
                }
         });*/
         //I have updated code by commenting the $.ajax method.and by writing following lines. 
    
       //I have also removed the '/' forward slash before EmpServletSnipet in following lines of code. 
    
        //Its working for fine but only for first chage event of select box after that when
    
        //I try to change the page from newly rendered select box Its not even invoke change event.
    
          $('#display').empty;
          $('#display').load('EmpServletSnipet',{page:$("#id_pageselect").val()});       
    });
    });
    </script>
    
    </head>
    <body>
    <div id="display" style="position:static; left:1003px; top:602px; width:500px; height:600px; z-index:10; overflow: scroll;">
    <a href="http://localhost:8080/webdynamic/EmpServlet?page=1">List</a>
    <select name="pageselect" id="id_pageselect">
    <c:forEach begin="1" end="${noOfPages}" var="i">
                <c:choose>
                    <c:when test="${currentPage eq i}">
                        <option value="${i}" selected>${i}</option>
                    </c:when>
                    <c:otherwise>
                        <option value="${i}">${i}</option>
                    </c:otherwise>
                </c:choose>
            </c:forEach>
    </select>
        <table border="1" cellpadding="5" cellspacing="5">
    <tr>
            <th>Emp ID</th>
            <th>Emp Name</th>
            <th>Salary</th>
            <th>Dept Name</th>
        </tr>
        <c:forEach var="employee" items="${employeeList}">
            <tr>
                <td>${employee.employeeId}</td>
                <td>${employee.employeeName}</td>
                <td>${employee.salary}</td>
                <td>${employee.deptName}</td>
            </tr>
        </c:forEach>
    </table>
    </div>
    

        

    EmpServlet.java servlet充当控制器。此servlet从jsp文件获取页面请求,并从DAO检索员工记录。 只给出了doGet和doPost方法。

    EmpServlet.java

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    int page = 1;
        int recordsPerPage = 5;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
                                 recordsPerPage);
        System.out.println("Employee list : "+list.size());
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("displayEmp.jsp");
        view.forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request,response);
    }
    

    EmpServletSnipet.java servlet用于获取ajax请求中所选页面的记录,并将一些代码snipet作为ajax响应发送

    将以id为显示呈现。 只给出了doGet和doPost方法。

    EmpServletSnipet.java

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("This is EmpServletSnipet");
    int page = 1;
        int recordsPerPage = 5;
        if(request.getParameter("page") != null)
        page = Integer.parseInt(request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,recordsPerPage);
        System.out.println("Employee list : "+list.size());
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        PrintWriter pw=response.getWriter();
    
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
    
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");
    
        pw.println("<a href=\"http://localhost:8080/webdynamic/EmpServlet?page=1\">List</a>");
        pw.println("<select name=\"pageselect\" id=\"id_pageselect\">");
            for(int i=1;i<=noOfPages;i++){
                if(i==page){
                    pw.println("<option value="+ i +" selected>"+ i +"</option>");
                }else{
                    pw.println("<option value="+ i +">"+ i +"</option>");
                }
            }
    
        pw.println("</select>");
    
        pw.println("<table border=\"1\" cellpadding=\"5\" cellspacing=\"5\">" +
                "<tr>" +
                "<th>Emp ID</th>" +
                "<th>Emp Name</th>" +
                "<th>Salary</th>" +
                "<th>Dept Name</th>" +
                "</tr>");
        Employee emp=null;
        for(int j=0;j<list.size();j++){
            emp=list.get(j);
            pw.println("<tr>" +
                    "<td>"+emp.getEmployeeId()+"</td>" +
                    "<td>"+emp.getEmployeeName()+"</td>" +
                    "<td>"+emp.getSalary()+"</td>" +
                    "<td>"+emp.getDeptName()+"</td>" +
                    "</tr>");
        }
    
        pw.println("</table>");
        pw.println("<td><a href=\"EmpServlet?page="+(page-1)+"\" id=\"prevpg\">Previous</a></td>");
        pw.println("<td><a href=\"EmpServlet?page="+(page+1)+"\" id=\"nextpg\">Next</a></td>");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request,response);
    }
    

    请指导我解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试

<script type="text/javascript">
function attach(){
    $('#id_pageselect').on('change',function(){
       $('#display').load('/EmpServletSnipet',{page:$(this).val()});
       // attach again, because the old #id_pageselect is lost!
       attach();
    });
}
$(function(){
    attach();
})
</script>