Struts2+Jquery實現ajax並返回json類型數據

摘要: 主要實現步驟如下: 1、JSP頁面使用腳本代碼執行ajax請求 2、Action中查詢出需要返回的數據,並轉換爲json類型模式數據 3、配置struts.xml文件 4、頁面腳本接受並處理數據 

網上看到很多關於Struts2+ajax+jquery+json的例子,但是很多都不完整,也看不明白,主要原因是返回jsno類型數據和原來的返回字符串類型數據不一樣,並且網友們實現步驟沒有說清楚,讓初學的朋友捉摸不透到底該怎麼做。

我做了個簡單的demo,供網友們學習,最後我會附上鍊接,可以下載整個demo.

首先需要的包(struts核心包和json需要的包):

struts核心包:

json需要的包:

commons-logging-*.jar在導入struts核心包的時候就導入了,所以導入json包的時候可以去掉這個包

頁面效果:

 

json_demo.jsp頁面(該頁面引用了jquery文件,我用的版本是jquery-1.8.2.js,如果使用版本不同,請自行修改):

01 <%@ page language="java" contentType="text/html; charset=UTF-8"
02     pageEncoding="UTF-8"%>
03 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
04 <html>
05 <head>
06 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
07 <title>Simpleton Demo | struts+ajax返回json類型數據</title>
08  
09 <link rel="shortcut icon" type="image/x-icon" href="images/Icon.png" />
10 <link rel="stylesheet" type="text/css" href="styles/base.css" />
11  
12 </head>
13 <body background="images/bg.gif">
14      
15     <div id="div_json">
16         <h5>錄入數據</h5>
17         <br />
18         <form action="#" method="post">
19             <label for="name">姓名:</label><input type="text" name="name" />
20             <label for="age">年齡:</label><input type="text" name="age" />
21             <label for="position">職務:</label><input type="text" name="position" />
22             <input type="button" class="btn" value="提交結果"/>
23         </form>
24         <br />
25         <h5>顯示結果</h5>
26         <br />
27         <ul>
28             <li>姓名:<span id="s_name">贊無數據</span></li>
29             <li class="li_layout">年齡:<span id="s_age">暫無數據</span></li>
30             <li class="li_layout">職務:<span id="s_position">暫無數據</span></li>
31         </ul>
32     </div>
33      
34     <div id="authorgraph"><img alt="" src="images/autograph.gif"></div>
35      
36     <script type="text/javascript" src="scripts/jquery-1.8.2.js"></script>
37     <script type="text/javascript">
38          
39         /* 提交結果,執行ajax */
40         function btn(){
41              
42             var $btn = $("input.btn");//獲取按鈕元素
43             //給按鈕綁定點擊事件
44             $btn.bind("click",function(){
45                  
46                 $.ajax({
47                     type:"post",
48                     url:"excuteAjaxJsonAction",//需要用來處理ajax請求的action,excuteAjax爲處理的方法名,JsonAction爲action名
49                     data:{//設置數據源
50                         name:$("input[name=name]").val(),
51                         age:$("input[name=age]").val(),
52                         position:$("input[name=position]").val()//這裏不要加","  不然會報錯,而且根本不會提示錯誤地方
53                     },
54                     dataType:"json",//設置需要返回的數據類型
55                     success:function(data){
56                         var d = eval("("+data+")");//將數據轉換成json類型,可以把data用alert()輸出出來看看到底是什麼樣的結構
57                         //得到的d是一個形如{"key":"value","key1":"value1"}的數據類型,然後取值出來
58                          
59                         $("#s_name").text(""+d.name+"");
60                         $("#s_age").text(""+d.age+"");
61                         $("#s_position").text(""+d.position+"");
62                          
63                     },
64                     error:function(){
65                         alert("系統異常,請稍後重試!");
66                     }//這裏不要加","
67                 });
68             });
69         }
70      
71         /* 頁面加載完成,綁定事件 */
72         $(document).ready(function(){          
73             btn();//點擊提交,執行ajax
74         });
75     </script>
76 </body>
77 </html>

JsonAction.java代碼

01 package com.simpleton.demo.action;
02  
03 import java.util.HashMap;
04 import java.util.Map;
05  
06 import javax.servlet.http.HttpServletRequest;
07  
08 import net.sf.json.JSONObject;
09  
10 import org.apache.struts2.interceptor.ServletRequestAware;
11  
12 import com.opensymphony.xwork2.ActionSupport;
13  
14 public class JsonAction extends ActionSupport implements ServletRequestAware{
15     private static final long serialVersionUID = 1L;
16      
17     private HttpServletRequest request;
18     private String result;
19  
20     public void setServletRequest(HttpServletRequest arg0) {
21         this.request = arg0;
22     }
23     public String getResult() {
24         return result;
25     }
26     public void setResult(String result) {
27         this.result = result;
28     }
29      
30     /**
31      * 處理ajax請求
32      * @return SUCCESS
33      */
34     public String excuteAjax(){
35          
36         try {
37             //獲取數據
38             String name = request.getParameter("name");
39             int age = Integer.parseInt(request.getParameter("age"));
40             String position = request.getParameter("position");
41              
42             //將數據存儲在map裏,再轉換成json類型數據,也可以自己手動構造json類型數據
43             Map<String,Object> map = new HashMap<String,Object>();
44             map.put("name", name);
45             map.put("age",age);
46             map.put("position", position);
47              
48             JSONObject json = JSONObject.fromObject(map);//將map對象轉換成json類型數據
49             result = json.toString();//給result賦值,傳遞給頁面
50         catch (Exception e) {
51             e.printStackTrace();
52         }
53         return SUCCESS;
54     }
55  
56  
57      
58 }

struts.xml中

01 <?xml version="1.0" encoding="UTF-8"?>
02 <!DOCTYPE struts PUBLIC
03     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
04     "http://struts.apache.org/dtds/struts-2.0.dtd">
05 <struts>
06      
07     <!--解決亂碼    -->
08     <constant name="struts.i18n.encoding" value="UTF-8"></constant>
09      
10     <package name="simpleton" extends="struts-default,json-default">
11          
12         <action name="*JsonAction" method="{1}"class="com.simpleton.demo.action.JsonAction">
13             <result name="fail"></result>
14             <!-- 返回json類型數據 -->
15             <result type="json">
16                 <param name="root">result<!-- result是action中設置的變量名,也是頁面需要返回的數據,該變量必須有setter和getter方法 --></param>
17             </result>
18         </action>
19          
20     </package>
21      
22 </struts>

這樣就可以完成一個簡單json數據類型傳遞的demo了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章