动态加表格的行和列,并添加值的小例子,用的是Hibernate Spring dwr。
dwr配置文件
<allow> <create creator="spring" javascript="userlogin" > <param name="beanName" value="userdao" /> <param name="location" value="applicationContext.xml"/> </create> <convert converter="bean" match="com.btm.login.entity.Users"> <param name="include" value="id,name,pass" /> </convert> </allow>
Spring配置文件 就一点儿
<bean id="userdao" class="com.btm.login.dao.UserLoginImpl"> <property name="sessionFactory" ref="sf" /> </bean>
web配置文件 (dwr的配置)
<!-- DWR配置 --> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
javascript代码
<script type='text/javascript' src='js/util.js'></script> <script type='text/javascript' src='js/engine.js'></script> <script type='text/javascript' src='dwr/interface/userlogin.js'></script> <script type="text/javascript"> <%-- 查询所有的用户--%> function findUsers(){ userlogin.findAllUsers( function (userList){ for(var i=0; i<userList.length;i++){ var newTr = tableTest.insertRow(1); //添加列 var newTd0 = newTr.insertCell(0); var newTd1 = newTr.insertCell(1); var newTd2 = newTr.insertCell(2); //设置列内容 newTd1.innerText = userList[i].pass; newTd0.innerText= userList[i].name; newTd2.innerHTML = '<input type=button class="btn" οnclick=deUsers('+userList[i].id+'); value="删除">'; } } ); } //删除用户 function deUsers(id){ userlogin.delUsers(id,function (bl){ }); window.location.reload(); findUsers(); } //添加用户 function addUsers(){ var userName = document.getElementById("name").value; var userPass = document.getElementById("pass").value; var us = {name:userName,pass:userPass} userlogin.addUsers(us,function(da){ alert(da); }); window.location.reload(); findUsers(); } </script>
页面代码
<body οnlοad="findUsers()">
用户名:
<input id="name" size="15">
<br>
密 码:
<input id="pass" size="15">
<br>
<input type="button" class="btn" οnclick="addUsers()" value="添加用户"
size="10">
<table id="tableTest" width="180" border="1" cellpadding="2"
cellspacing="0" bordercolorlight="#000000" bordercolordark="#FFFFFF"
bgcolor="#FFFFEE">
<tr>
<td>
用户名
</td>
<td>
密码
</td>
<td>
操作
</td>
</tr>
</table>
</body>
下面是完整例子dwr index是一个登陆验证 addTable.jsp是上面的代码,后台很简单就不贴了。