今天在用struts2 异步请求从后台传一个对象到前台时遇到了一个小小的问题,现在此作一个标记,把主要的代码贴上以作备忘。
struts.xml
<action name="getSystemContactorInfo" class="userAction" method="getSystemContactorInfo">
<result type="json">
<param name="includeProperties">systemContactor\.userName,systemContactor\.cellPhone,
systemContactor\.notesMail
</param>
<!-- <param name="includeProperties">systemContactor</param> 这样不对-->
<!-- <param name="includeProperties">systemContactor.*</param> 这样同样不正确-->
</result>
</action>
UserAction
public String getSystemContactorInfo() {
UserModel systemContactor = new UserModel();
systemContactor.setUserName("张三");
systemContactor.setCellPhone("13240151465");
systemContactor.setNotesMail("test@126.com");
return Action.SUCCESS;
}
UserModel
public class UserModel{
private String userName;
private String cellPhone;
private String notesMail;
//省略get、set方法
}
jsp页面中
$.ajax({
type:'post',
url: 'getSystemContactorInfo.action',
dataType: 'json',
async: true,
success: function showContent(json) {
var userInfo = json.systemContactor;
$("#userName").html(userInfo.userName);
$("#cellPhone").html(userInfo.cellPhone);
$("#notesMail").html(userInfo.notesMail);
}
});
<param name="includeProperties">systemContactor</param> 当systemContactor为一个字串或数字时可以这样写
<param name="includeProperties">systemContactor.*</param>当systemContactor为list时可这样传
到现在也不是太明白当systemContactor为一个对象时为什么不能直接写在里面,在此标记一下。嗯,有必要去看下官方的api了