標籤:detail error imp serial roo new enter 姓名 center
一、jar包
首先引入Struts和json所需的jar包。
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaXRteWhvbWUxOTkw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />
二、前台代碼
<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>
示比例如以:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaXRteWhvbWUxOTkw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" />
itmyhome
出處:http://blog.csdn.net/itmyhome1990/article/details/41960911
原始碼:download
Struts2 ajax json使用介紹