我想在点击按钮后自动增加表格行

时间:2014-03-12 07:55:59

标签: java javascript jsp

*****

嗨,我的问题是自动增加表格行。实际上,当我单击GET按钮时,产品类型和产品名称值来自数据库。在获取这些值之后,我将再次基于该id给出另一个id,因为值将会到来。但它没有进入另一排。这是我的java代码和jsp

Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
    while(rs.next())
    {
        i++;
        request.getSession().setAttribute("edit","success");
        request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
        request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
        request.getSession().setAttribute("strength", rs.getString("Strength_v"));
        request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
        request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
        request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
        request.getSession().setAttribute("uom", rs.getString("UOM_v"));
        request.getSession().setAttribute("formE", rs.getString("FormE_v"));
        request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
    }
    if(i==0)
    {
        request.getSession().setAttribute("edit", "fail");
    }
}
catch(Exception e)


jsp code

<tr>  
    <td>
        <input class="textfield-form-date-req" type="text" id="pro_type">
    </td>
    <%
        if(editStatus =="success")
        {
    %>
    <script type="text/javascript">
        document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
    </script>
    <%
    }
    <td>
        <input class="textfield-form-date-req" type="text" id="pro_id">
    </td>
    <% 
        if(editStatus =="success")
        {
    %>
    <scripttype="text/javascript">
        document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
    </script>
    <% 
    }
    %>                  
    <td></td>
    <td></td>
    <td></td> 
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</tr>

1 个答案:

答案 0 :(得分:1)

我使用ajax为您创建了一个示例。它从server side获取数据并将其附加到现有表中。

我使用的jar文件是,

  1. jackson-all-1.9.0.jar - 将java对象转换为json格式

  2. servlet-api-2.4.jar - for servlet

  3. 我的TableAppend.jsp将是,

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!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=UTF-8">
    <title>Insert title here</title>
    <script
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
        </script>
    <script type="text/javascript">
            $(document).ready(function() {
    
                //alert("DOM is ready");
    
            });
    
            function sendData() {
    
                $.ajax({
                    type : 'POST',
                    url : "TableAppend",
                    data : "name=" + $('#name').val() + "&age=" + $('#age').val()
                            + "&sid=" + new Date(),
                    dataType : 'html',
                    success : function(result) {
                        //alert("Result ::::>>> "+result);
                        if(result != null && $.trim(result) != "" && result != undefined){
                            var json = JSON.parse(result);
                            //alert(json.name);
                            //alert(json.age);
                            appendToTable(json.name, json.age);
                        }
    
                    },
                    error : function(e) {
                        alert('Error in Processing');
                    }
    
                });
            }
    
            function appendToTable(name, age) {
                var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
                $('#mytable').append(tr);
            }
        </script>
    </head>
    <body>
        Name :
        <input type="text" id="name" name="name" /> Age :
        <input type="text" id="age" name="age" />
    
        <input type="button" value="Append to table" onclick="sendData()">
        <br></br>
        <br></br>
        <br></br>
        <table id="mytable" border="1">
            <tbody>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
                <tr>
                    <td>HumanBeing</td>
                    <td>25</td>
                </tr>
                <tr>
                    <td>Saideep</td>
                    <td>26</td>
                </tr>
            </tbody>
        </table>
    
    </body>
    </html>
    

    我的TableAppend.java servlet将是,

    public class TableAppend extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * Default constructor. 
         */
        public TableAppend() {
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
    
            response.setCharacterEncoding("UTF-8");
            response.setContentType("UTF");
            PrintWriter out = response.getWriter();
    
            request.setCharacterEncoding("UTF-8");
    
            String name = request.getParameter("name");
            String age = request.getParameter("age");
            String json ="";
            System.out.println("-----------------");
            if(name != null && age != null){
                TableAppendPojo obj = new TableAppendPojo();
                obj.setName(name);
                obj.setAge(age);
    
                ObjectMapper mapper = new ObjectMapper();
                json = mapper.writeValueAsString(obj);
                System.out.println("json : "+json);
            }
            out.println(json);
        }
    
    }
    

    然后java class将是,

    public class TableAppendPojo {
    
        private String name;
        private String age;
    
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
    
    
    }
    

    注意:请在您的代码中应用上述逻辑。在您的情况下,您不需要提供UI的数据。您从database中的servlet检索数据。因此,请将检索到的数据从database转换为json格式,然后将其附加到table

    希望这有帮助。