摘要: 主要实现步骤如下: 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"> |
06 |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> |
07 |
<title>Simpleton Demo | struts+ajax返回json类型数据</title> |
09 |
<link rel="shortcut icon" type="image/x-icon" href="images/Icon.png" /> |
10 |
<link rel="stylesheet" type="text/css" href="styles/base.css" /> |
13 |
<body background="images/bg.gif"> |
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="提交结果"/> |
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> |
34 |
<div id="authorgraph"><img alt="" src="images/autograph.gif"></div> |
36 |
<script type="text/javascript" src="scripts/jquery-1.8.2.js"></script> |
37 |
<script type="text/javascript"> |
42 |
var $btn = $("input.btn");//获取按钮元素 |
44 |
$btn.bind("click",function(){ |
48 |
url:"excuteAjaxJsonAction",//需要用来处理ajax请求的action,excuteAjax为处理的方法名,JsonAction为action名 |
50 |
name:$("input[name=name]").val(), |
51 |
age:$("input[name=age]").val(), |
52 |
position:$("input[name=position]").val()//这里不要加"," 不然会报错,而且根本不会提示错误地方 |
54 |
dataType:"json",//设置需要返回的数据类型 |
55 |
success:function(data){ |
56 |
var d = eval("("+data+")");//将数据转换成json类型,可以把data用alert()输出出来看看到底是什么样的结构 |
57 |
//得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来 |
59 |
$("#s_name").text(""+d.name+""); |
60 |
$("#s_age").text(""+d.age+""); |
61 |
$("#s_position").text(""+d.position+""); |
72 |
$(document).ready(function(){ |
JsonAction.java代码
01 |
package com.simpleton.demo.action; |
03 |
import java.util.HashMap; |
06 |
import javax.servlet.http.HttpServletRequest; |
08 |
import net.sf.json.JSONObject; |
10 |
import org.apache.struts2.interceptor.ServletRequestAware; |
12 |
import com.opensymphony.xwork2.ActionSupport; |
14 |
public class JsonAction extends ActionSupport implements ServletRequestAware{ |
15 |
private static final long serialVersionUID = 1L; |
17 |
private HttpServletRequest request; |
18 |
private String result; |
20 |
public void setServletRequest(HttpServletRequest arg0) { |
23 |
public String getResult() { |
26 |
public void setResult(String result) { |
34 |
public String excuteAjax(){ |
38 |
String name = request.getParameter("name"); |
39 |
int age = Integer.parseInt(request.getParameter("age")); |
40 |
String position = request.getParameter("position"); |
42 |
//将数据存储在map里,再转换成json类型数据,也可以自己手动构造json类型数据 |
43 |
Map<String,Object> map = new HashMap<String,Object>(); |
44 |
map.put("name", name); |
46 |
map.put("position", position); |
48 |
JSONObject json = JSONObject.fromObject(map);//将map对象转换成json类型数据 |
49 |
result = json.toString();//给result赋值,传递给页面 |
50 |
} catch (Exception e) { |
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"> |
08 |
<constant name="struts.i18n.encoding" value="UTF-8"></constant> |
10 |
<package name="simpleton" extends="struts-default,json-default"> |
12 |
<action name="*JsonAction" method="{1}"class="com.simpleton.demo.action.JsonAction"> |
13 |
<result name="fail"></result> |
16 |
<param name="root">result<!-- result是action中设置的变量名,也是页面需要返回的数据,该变量必须有setter和getter方法 --></param> |
这样就可以完成一个简单json数据类型传递的demo了。
下面附上源码文件(百度网盘),基于eclipse开发,导入即可运行:http://pan.baidu.com/share/link?shareid=2994183962&uk=1646424500
- Struts2+Jquery实现ajax并返回json类型数据
来源于:http://my.oschina.net/simpleton/blog/139212 摘要 主要实现步骤如下: 1.JSP页面使用脚本代码执行ajax请求 2.Action中查询出需要返回的 ...
- 使用jQuery发送POST,Ajax请求返回JSON格式数据
问题: 使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code" ...
- struts2学习笔记--使用struts2插件实现ajax处理(返回json数据)
贴一个简单的例子,通过jquery的post调用action,定义一个对象User,有name和age属性,实例化几个对象,以json的格式返回到jsp,在前台页面显示出来,模拟用户列表. 导入相关j ...
- Flask(python)异步(ajax)返回json格式数据
主要讨论两个问题,第一个是关于json.dumps 与jsonify区别,第二个是几种异步的区别(见jQuery中的$.getJSON.$.ajax.$.get.$.post的区别). json.du ...
- Ajax返回xml类型数据
ajax可以返回文本类型数据和xml类型数据,xml是计算机通用语言 可以使用js解析返回xml类型数据的dom对象 前端页面 <!doctype html> <html lang= ...
- jquery ajax调用返回json格式数据处理
Ajax请求默认的都是异步的 如果想同步 async设置为false就可以(默认是true) var html = $.ajax({ url: "some.php", async: ...
- jquery通过ajax方法获取json数据不执行success
1.jquery通过ajax方法获取json数据不执行success回调 问题描述:jquery通过ajax方法获取json数据不执行success回调方法 问题原因:json格式存在问题或不符合标准 ...
- Ajax请求php返回json对象数据中包含有数字索引和字符串索引,在for in循环中取出数据的顺序问题
//php中的数组数据格式 Array ( [all] => Array ( [title] => ALL [room_promotion_id] => all ) [best_av ...
- jQuery中ajax如何返回值到上层函数
jQuery中ajax如何返回值到上层函数 一.总结 一句话总结: ajax的同步操作即可,设置 async: false, 二.jquery的同步操作 var can_submit=true; $. ...
随机推荐
- php中计算中文字符串长度、截取中文字符串
在做PHP开发的时候,由于我国的语言环境问题,所以我们常常需要对中文进行处理.在PHP中,我们都知道有专门的mb_substr和mb_strlen函数,可以对中文进行截取和计算长度,但是,由于这些函数 ...
- mongodb spring
可参考 http://blog.csdn.net/cuiran/article/details/8287204 我修改后的代码 http://pan.baidu.com/s/1mgJYbaC
- 【好程序员笔记分享】——UIView与CALayer详解
-iOS培训,iOS学习-------型技术博客.期待与您交流!------------ UIView与CALayer详解 研究Core Animation已经有段时间了,关于Core Animati ...
- log4Net使用的四个步骤
第一步.引入程序集,并建立配置文件,放在根目录下config文件夹里.配置文件如下: <?xml version="1.0" encoding="utf-8&quo ...
- 职员时序安排lingo求解
大家好,我是小鸭酱,博客地址为:http://www.cnblogs.com/xiaoyajiang !职员时序安排模型 题目: 一项工作一周七天都需要有人,每天所需的最少职工数为20,16,13,1 ...
- Swift 可选链-备
在Swift程序表达式中会看到问号(?)和感叹号(!),它们代表什么含义呢?这些符号都与可选类型和可选链相关,下面来看看可选链. 可选链: 类图: 它们之间是典型的关联关系类图.这些类一般都是实体类, ...
- repo init 时gpg: 无法检查签名:找不到公钥
i found a solution here: http://www.marshut.com/wrrts/repo-release-1-12-4.html Sorry, I realized tod ...
- CCI_chapter 2 Linked Lists
2.1 Write code to remove duplicates from an unsorted linked list /* Link list node */ struct node { ...
- LeetCode_Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combina ...
- pythonchallenge学到的python内置函数整理
第0关: 计算x的n次方: x**n 第一关: maketrans(from,to):建立一个翻译规则,将from翻译成to的翻译规则,因为要从from翻译成to,所以俩个参数的长度必须一致 tran ...