通过ajax从jsp页面传输数据到web层,并从web层返回数据给jsp页面

时间:2024-10-14 16:06:50
jsp中ajax代码:
1 $.ajax({
var id = $("#studentid").val();//获取标签中的学生id
url:'${pageContext.request.contextPath}/student/stu_delStudent.action?studentid='+id,
data:'',
type:'POST',
dataType:'json',
async:false,
success:function(data){
alert(data.message);
} });
action中的代码:
1 public class StudentAction extends ActionSupport{
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
} @Resource
private StudentService studentService; public String delStudent() throws Exception{
//接收请求数据
int studentid = ServletActionContext.getRequest().getParameter("studentid");
studentSerivce.delByStudentId(studentid);
//创建一个JSON对象
JSONObject json = new JSONObject();
json.put(“message",删除成功");//将返回信息保存在JSON对象中
HttpServletResponse response = ServletActionContext.getResponse();
//设置响应编码格式,防止乱码
response.setContentType("text/html;charset=UTF-8");
//将数据以json格式响应给ajax
response.getWriter().write(json.toString()); return null;
}
}