AJAX在Struts2中使用

时间:2022-06-07 21:39:51

前台页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %> <!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 type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
//1点击删除的时候,确定删除吗?
$(".delete").click(function(){
var lastName=$(this).next(":input").val();
var flag=confirm("确定要"+lastName+"删除吗?");
if(flag){
//删除,使用ajax的方式
var url=this.href;
var args={"time":new Date()};
$.post(url,args,function(data){
if(data=="1"){
alert("删除成功");
$tr.remove();
}else{
alert("删除失败")
}
});
}
//取消超链接的默认行为
return false;
});
})
</script>
</head>
<body> <h4>Employee List Page</h4> <s:if test="#request.employees == null || #request.employees.size() == 0">
没有任何员工信息
</s:if>
<s:else>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>ID</td>
<td>LASTNAME</td>
<td>EMAIL</td>
<td>BIRTH</td>
<td>CREATETIME</td>
<td>DEPT</td>
<td>delete</td>
</tr>
<s:iterator value="#request.employees">
<tr>
<td>${id }</td>
<td>${lastName }</td>
<td>${email }</td>
<td>${birth }</td>
<td>${createtime }</td>
<td>${department.departmentName } </td>
<td><a href="emp-delete?id=${id }" class="delete">Delete</a>
<input type="hidden" value="${lastName }">
</td> </tr>
</s:iterator>
</table>
</s:else> </body>
</html>

ACTION中:

public String delete(){

        try {
employeeService.deleteEmployee(id);
inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
try {
inputStream=new ByteArrayInputStream("0".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} }
return "delete";
} private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}

struts.xml文件中:

<package name="default" namespace="/" extends="struts-default">
<action name="emp-*" class="employeeAction"
method="{1}">
<result name="list">/emp-list.jsp</result> <result type="stream" name="delete">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action> </package>