这个也比较简单
先贴上struts.xml
<package name="demo2" extends="json-default" namespace="/demo2"> <action name="*_*" class="com.lan.action.json.{1}Action" method="{2}"> <result name="success" type="json"></result> </action> </package>
贴action
package com.lan.action.json; import org.apache.struts2.json.annotations.JSON; import com.lan.Bean.Person; import com.opensymphony.xwork2.ActionSupport; /** * Struts2-Json 返回一个对象 * * @author lan * */ public class Demo2Action extends ActionSupport { private Person person; private int add; private String type; public String getEntity() { this.person = new Person(); person.setName("lan-"+type); person.setAge(10 + add); person.setSex("M"); return SUCCESS; } public Person getPerson() { return person; } @JSON(name = "person") public void setPerson(Person person) { this.person = person; } public int getAdd() { return add; } public void setAdd(int add) { this.add = add; } public String getType() { return type; } public void setType(String type) { this.type = type; } }贴js,这个data 不是要传递的对象,直接打印data显示的是
{"add":20,"entity":"success","person":{"age":30,"name":"lan-null","sex":"M"}
/* * ajax 实体类 */ //load /* $(function() { $("#entity").load("demo2/Demo2_getEntity.action", { add : "20" }, function(data) { // alert(data.person.age); // $(this).html(data.person.age); $("#load-person-name").html(data.person.name); $("#load-person-age").html(data.person.age); $("#load-person-sex").html(data.person.sex); }); }); */ // post $(function() { $("#button-entity-001").click(function() { $.post("demo2/Demo2_getEntity.action", { add : "100", type : "post" }, function(data) { $("#load-person-name").html(data.person.name); $("#load-person-age").html(data.person.age); $("#load-person-sex").html(data.person.sex); }); }); }); // get $(function() { $("#button-entity-002").click(function() { $.get("demo2/Demo2_getEntity.action", { add : "30", type : "get" }, function(data) { $("#load-person-name").html(data.person.name); $("#load-person-age").html(data.person.age); $("#load-person-sex").html(data.person.sex); }); }); }); // ajax $(function() { $("#button-entity-003").click(function() { $.ajax({ url : "demo2/Demo2_getEntity.action", type : "post", data : "add=" + "50" + "&type=" + "ajax", success : function(data) { $("#load-person-name").html(data.person.name); $("#load-person-age").html(data.person.age); $("#load-person-sex").html(data.person.sex); } }); }); });