一、jar包
首先引入Struts和json所需的jar包。
二、前台代码
<body> <form id="myform"> <table> <tr> <td>姓名:</td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td>性别:</td> <td> <input type="radio" name="sex" value="1"> 男 <input type="radio" name="sex" value="0"> 女 </td> </tr> <tr> <td>年龄:</td> <td> <select name="age"> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> </select> </td> </tr> <tr> <td colspan="2"> <input type="button" id="ajaxBtn" value="提交" /> </td> </tr> </table> </form> <div id="msg"></div> </body>
<script type="text/javascript"> $(function() { $("#ajaxBtn").click(function() { var params = $("#myform").serialize(); $.ajax( { type : "POST", dataType : "json", url : "RegisterAction.action", data : params, success : function(data) { var obj = eval('(' + data + ')'); //将数据转换为json类型 $("#msg").html("您提交的信息为: 姓名:"+obj.name+" , 性别:"+obj.sex+" , 年龄:"+obj.age); }, error : function(data, status, e){ alert("error"); } }); }) }) </script>
三、Action
import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class RegisterAction { private String name; private String sex; private String age; private String result; public String register() { Map<String, Object> map = new HashMap<String, Object>(); map.put("msg", true); map.put("name", name); map.put("sex", sex==null?"":("1".equals(sex)?"男":"女")); map.put("age", age); JSONObject json = JSONObject.fromObject(map);//将map对象转换成json类型数据 result = json.toString();// 将result传给页面 return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
四、Struts配置
<struts> <package name="build" extends="json-default"> <action name="RegisterAction" method="register" class="com.home.RegisterAction"> <result type="json"> <param name="root">result</param> <!-- result为action中要返回的数据 --> </result> </action> </package> </struts>
示例如下图:
出处:blog.ytso.com/article/details/41960911
源码:download
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/14374.html