jsp中ajax代码:
1 $.ajax({
2 var id = $("#studentid").val();//获取标签中的学生id
3 url:'${pageContext.request.contextPath}/student/stu_delStudent.action?studentid='+id,
4 data:'',
5 type:'POST',
6 dataType:'json',
7 async:false,
8 success:function(data){
9 alert(data.message);
10 }
11
12 });
action中的代码:
1 public class StudentAction extends ActionSupport{
2 private Student student;
3 public Student getStudent() {
4 return student;
5 }
6 public void setStudent(Student student) {
7 this.student = student;
8 }
9
10 @Resource
11 private StudentService studentService;
12
13 public String delStudent() throws Exception{
14 //接收请求数据
15 int studentid = ServletActionContext.getRequest().getParameter("studentid");
16 studentSerivce.delByStudentId(studentid);
17 //创建一个JSON对象
18 JSONObject json = new JSONObject();
19 json.put(“message",删除成功");//将返回信息保存在JSON对象中
20 HttpServletResponse response = ServletActionContext.getResponse();
21 //设置响应编码格式,防止乱码
22 response.setContentType("text/html;charset=UTF-8");
23 //将数据以json格式响应给ajax
24 response.getWriter().write(json.toString());
25
26 return null;
27 }
28 }
不能只满足于写完代码运行结果正确就完事,时常考虑如何让代码更加简练更加容易维护、容易扩展和复用,只有这样才可以真正得到提高
--《来自大话设计模式》