標籤:ajax j2ee struct
如 Model類如下,Teacher,public class Teacher{
private Integer id;
priavte String name;
private School school;
}
而School, public class School{
private Integer id;
priavte String name;
}
上面的Teacher,School省去了getter和setter方法。
action類如下
public class TeacherAction extends ActionSupport implents ModelDriven<Teacher>{
public String saveTeacher(){
if(.teacher.getSchool() != null && teacher.getSchool().getId() != null){
teacher.setSchool(schoolDao.load(teacher.getSchool().getId()));
}
Teacher teacher= teacherDao.save(teacher);
return SUCCESS;
}
}
該action配置如下
<package name="ajax" extends="json-default">
<action name=teacher_"*" class="com.zxt.action.TeacherAction method={1}">
<!-- 將傳回型別設定為json -->
<result type="json"></result>
</action>
</package>
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=ISO-8859-1">
<title>測試</title>
<script type="text/javas cript" src="include/js/jquery-1.4.2.min.js"></script>
<script type="text/javas cript">
$(function() {
$("#tj").click(function() {
//提交的參數,name和inch是和struts action中對應的接收變數
var params = {
“ school.id” : $("#xm").val(),
“ name” : $("#xm1").val(
};
$.ajax({
type: "POST",
url: "teacher_findTeacherByScholl.action",
data: params,
dataType:"text", //ajax返回值設定為text(json格式也可用它返回,可列印出結果,也可設定成json)
success: function(json){
var obj = $.parseJSON(json); //使用這個方法解析json
var state_value = obj.teacher //result是和action中定義的result變數的get方法對應的
alert(state_value);
},
error: function(json){
alert("json=" + json);
return false;
}
});
});
});
</script>
</head>
<body>
<span>學校:</span><input id="xm" type="text">
<br/>
<span>名字:</span><input id="xm1" type="text">
<br/>
<input type="button" value="提交" id="tj">
</body>
</html>