首先需导入包:ezmorph-1.0.4.jar
Action中的调用的方法:
public void getObject(){
try {
if(cname!=null&& !cname.equals("")){
u=udao.findByName(cname);
JSONObject obj=new JSONObject();
obj.put("house", u.getHouse());//u是一个User对象
actionUtil.sendStringToClient(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Json的封装类:
public class ActionUtil {
/**
* 将指定的字符串发送到客户端
*
* @param content
* @throws Exception
*/
public void sendStringToClient(String content) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(content);
}
public void sendSuccessToClient() throws Exception{
this.sendStringToClient("success");
}
/**
* 将List集合转换成对应的Json字符串
* @param list 待转换的List集合
* @return Json字符串
* @throws Exception
*/
public String generJsonStringFromList(List list) throws Exception {
JSONArray array = JSONArray.fromObject(list);
return array.toString();
}
public void sendJsonStringFromList(List list)throws Exception{
this.sendStringToClient(this.generJsonStringFromList(list));
}
}
Struts.xml中的配置:
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"></result-type>
</result-types>
<action name="stipendObject" class="stipendformAction" method="getObject">
<result type="json"></result>
</action>
jsp页面中ajax:
//选择下拉列表中的某一项,其他显示框显示相应信息
function change(){
var obj = document.getElementById("name"); //定位id
var index = obj.selectedIndex; // 选中索引
var text = obj.options[index].text; // 选中文本
$.ajax({
type:'POST',
data:{cname:text},
success:function(data){ var obj=eval("("+data+")"); $("#house").val(obj.house); } });
}
jsp页面中的下拉列表
<s:select id="name" name="stipendform.name" list="ulist" class="input"
listKey="id" listValue="username" theme="simple" headerKey="0" headerValue="--------请选择员工-------"
style="margin-bottom:5px;" onchange="change();" ></s:select>
若实现级联菜单:
二级菜单用<select id="c2" name="book.category2.id"
style="margin-bottom:5px;"><option value="">二级</option></select>
$.ajax({
type :"POST",
url : "cate2list.action",
data : {con : text},
// dataType : "json",
success : function(data) {
alert(data);
var obj = eval("(" + data + ")");
alert(obj.list);
//$("#c2").val(obj.list);
var e = document.form1.c2;
for (var i=0; i<obj.list.length; i++) e.options.add(new Option(obj.list[i], obj.list[i]));
},
error : function() {
alert('加载失败!');
}
});
public void getObject() {
try {
if (con != null && !con.equals("")) {
ActionUtil actionUtil = new ActionUtil();
JSONObject obj = new JSONObject();
c2list = c2Dao.findByCate1Id(c1Dao.findByName(con).getId());
List<String> str=new ArrayList<String>();
//将对象数组转换为字符串数组 对象数组obj.put会出错
for(int i=0;i<c2list.size();i++){
str.add(c2list.get(0).getName());
}
obj.put("list", str);
actionUtil.sendStringToClient(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}