日期:2014-05-16 浏览次数:20393 次
<%@ taglib prefix="s" uri="/struts-tags"%> <SCRIPT type="text/javascript" src="js/jquery-1.2.6.js"></script> <SCRIPT type="text/javascript"> $(document).ready(function () { $("button").click(function () { var params = $("input").serialize(); $.ajax({url:"jsonAction.action", type:"post", dataType:"json", data:params, success : update_page}); }); }); function update_page(result) { alert('abcd'); var json = eval('(' + result + ')'); var str = "First Name:" + json.firstname + "<br />"; str += "Last Name:" + json.lastname + "<br />"; str += "age:" + json.age + "<br />"; alert(str); $("#result").html(str); } </SCRIPT> <div id="result"> </div> <s:form action="" method="post"> <s:textfield label="First Name" name="user.firstname" /> <s:textfield label="Last Name" name="user.lastname" /> <s:textfield label="age" name="user.age" /> <button>Submit</button> </s:form>
public class User implements Serializable { private Integer id; private String firstname; private String lastname; private Integer age; // 省略get, set方法 }
public class JsonAction extends ActionSupport { private User user; // 用于记录返回结果 private String result; // 省略相应的get和set方法 @SuppressWarnings("static-access") public String execute() throws Exception { // 将要返回的user实体对象进行json处理 JSONObject jo = JSONObject.fromObject(user); // 打印一下,格式如下 //{"age":3,"firstname":"xxx","id":0,"lastname":"xxxxx"} System.out.println(jo); // 调用json对象的toString方法转换为字符串然后赋值给result this.result = jo.toString(); return this.SUCCESS; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2" extends="json-default"> <action name="jsonAction" class="com.marinda.action.JsonAction"> <result type="json"> <!-- 因为要将reslut的值返回给客户端,所以这样设置 --> <!-- root的值对应要返回的值的属性 --> <param name="root">result</param> <!-- <param name="ignoreHierarchy">false</param> <param name="noCache">true</param> <param name="excludeNullProperties">true</param> --> </result> </action> </package> </struts>
WARN ServletUrlRenderer:45 - No configuration found for the specified action: '' in namespace: ''. Form action defaulting to 'action' attribute's literal value.
<s:form action="" method="post" onsubmit="return false;">