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,如果使用版本不同,请自行修改):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
< html >
< head >
< meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
< title >Simpleton Demo | struts+ajax返回json类型数据</ title >
 
< link rel = "shortcut icon" type = "image/x-icon" href = "images/Icon.png" />
< link rel = "stylesheet" type = "text/css" href = "styles/base.css" />
 
</ head >
< body background = "images/bg.gif" >
     
     < div id = "div_json" >
         < h5 >录入数据</ h5 >
         < br />
         < form action = "#" method = "post" >
             < label for = "name" >姓名:</ label >< input type = "text" name = "name" />
             < label for = "age" >年龄:</ label >< input type = "text" name = "age" />
             < label for = "position" >职务:</ label >< input type = "text" name = "position" />
             < input type = "button" class = "btn" value = "提交结果" />
         </ form >
         < br />
         < h5 >显示结果</ h5 >
         < br />
         < ul >
             < li >姓名:< span id = "s_name" >赞无数据</ span ></ li >
             < li class = "li_layout" >年龄:< span id = "s_age" >暂无数据</ span ></ li >
             < li class = "li_layout" >职务:< span id = "s_position" >暂无数据</ span ></ li >
         </ ul >
     </ div >
     
     < div id = "authorgraph" >< img alt = "" src = "images/autograph.gif" ></ div >
     
     < script type = "text/javascript" src = "scripts/jquery-1.8.2.js" ></ script >
     < script type = "text/javascript" >
         
         /* 提交结果,执行ajax */
         function btn(){
             
             var $btn = $("input.btn");//获取按钮元素
             //给按钮绑定点击事件
             $btn.bind("click",function(){
                 
                 $.ajax({
                     type:"post",
                     url:"excuteAjaxJsonAction",//需要用来处理ajax请求的action,excuteAjax为处理的方法名,JsonAction为action名
                     data:{//设置数据源
                         name:$("input[name=name]").val(),
                         age:$("input[name=age]").val(),
                         position:$("input[name=position]").val()//这里不要加","  不然会报错,而且根本不会提示错误地方
                     },
                     dataType:"json",//设置需要返回的数据类型
                     success:function(data){
                         var d = eval("("+data+")");//将数据转换成json类型,可以把data用alert()输出出来看看到底是什么样的结构
                         //得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来
                         
                         $("#s_name").text(""+d.name+"");
                         $("#s_age").text(""+d.age+"");
                         $("#s_position").text(""+d.position+"");
                         
                     },
                     error:function(){
                         alert("系统异常,请稍后重试!");
                     }//这里不要加","
                 });
             });
         }
     
         /* 页面加载完成,绑定事件 */
         $(document).ready(function(){          
             btn();//点击提交,执行ajax
         });
     </ script >
</ body >
</ html >

JsonAction.java代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.simpleton.demo.action;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import net.sf.json.JSONObject;
 
import org.apache.struts2.interceptor.ServletRequestAware;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class JsonAction extends ActionSupport implements ServletRequestAware{
     private static final long serialVersionUID = 1L;
     
     private HttpServletRequest request;
     private String result;
 
     public void setServletRequest(HttpServletRequest arg0) {
         this .request = arg0;
     }
     public String getResult() {
         return result;
     }
     public void setResult(String result) {
         this .result = result;
     }
     
     /**
      * 处理ajax请求
      * @return SUCCESS
      */
     public String excuteAjax(){
         
         try {
             //获取数据
             String name = request.getParameter( "name" );
             int age = Integer.parseInt(request.getParameter( "age" ));
             String position = request.getParameter( "position" );
             
             //将数据存储在map里,再转换成json类型数据,也可以自己手动构造json类型数据
             Map<String,Object> map = new HashMap<String,Object>();
             map.put( "name" , name);
             map.put( "age" ,age);
             map.put( "position" , position);
             
             JSONObject json = JSONObject.fromObject(map); //将map对象转换成json类型数据
             result = json.toString(); //给result赋值,传递给页面
         } catch (Exception e) {
             e.printStackTrace();
         }
         return SUCCESS;
     }
 
 
     
}

struts.xml中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
     "http://struts.apache.org/dtds/struts-2.0.dtd">
< struts >
     
     <!--解决乱码    -->
     < constant name = "struts.i18n.encoding" value = "UTF-8" ></ constant >
     
     < package name = "simpleton" extends = "struts-default,json-default" >
         
         < action name = "*JsonAction" method = "{1}" class = "com.simpleton.demo.action.JsonAction" >
             < result name = "fail" ></ result >
             <!-- 返回json类型数据 -->
             < result type = "json" >
                 < param name = "root" >result <!-- result是action中设置的变量名,也是页面需要返回的数据,该变量必须有setter和getter方法 --> </ param >
             </ result >
         </ action >
         
     </ package >
     
</ struts >

这样就可以完成一个简单json数据类型传递的demo了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值