struts2+jquery 实现ajax无刷新更新数据

前几天为了实现一个struts 的 ajax无刷新更新数据的例子,发现网上资料很少,很多已经过时或者链接都失效了

不过整合他们的资料,加上自己的研究,终于实现了效果

要求:1、各个学院提交学生数据到服务器,要求ajax 无刷新更新数据,

2、服务器端返回“更新成功”的提示窗口;

3、之后,使用jquery 更新input输入框的value值,为实现jquery 打印页面局部数据做准备。

此处使用struts2的第二种方法,(修改struts 配置文件,增加ajax package 的方式实现)

一、success.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@page import="org.apache.struts2.ServletActionContext"%>
<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@page import="qau.edu.entity.User"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>统计表</title>
<link href="images/style.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="js/jquery-1.8.2.js"></script>  //必须引入的jquery类库

</head>

<%
	if (ServletActionContext.getRequest().getSession()
			.getAttribute("user") == null) {
		out.print("<script>alert(‘请登录‘);location.href=‘index.jsp‘</script>");
	}
%>

<body>
	<div class="table">
		<br />

		<form action="#" method="post">
			<input type="hidden" id="tuser" name="tongji.user" value="user" />
			<div id="jsexport">
			<br /> 
			<p align="center">
				<font size="+2">汇总结果</font>
			</p>
			<br />
			<table border="3" align="center">
				<tr>
					<th width="120" rowspan="2" scope="col">学院名称</th>
					<th width="86" rowspan="2" scope="col">学生总数</th>
					<th width="60" rowspan="2" scope="col">返校学生数</th>
					<th width="65" rowspan="2" scope="col">实习学生数</th>
					<th colspan="6" scope="col">未返校学生数</th>
					<th width="93" rowspan="2" scope="col">统计人签字</th>
					<th width="101" rowspan="2" scope="col">学工班主任签字</th>
				</tr>
				<tr>
					<td width="89">未购票/车次晚点</td>
					<td width="40">生病</td>
					<td width="50">家中有事</td>
					<td width="83">休学 /退学/ 转学</td>
					<td width="59">联系不上</td>
					<td width="63">未返校合计</td>
				</tr>

				<tr>
					<td style="text-align:center">${tongji.name}</td>
					<td><input type="number" id="stunum"
						style="border-style:none;width:90px" name="tongji.stunum"
						value="${tongji.stunum}" readonly="readonly" /></td>
					<td><input type="number" id="fxstu"
						style="border-style:none;width:90px" name="tongji.fxstu"
						value="${tongji.fxstu}" /></td>
					<td><input type="number" id="sxstu"
						style="border-style:none;width:90px" name="tongji.sxstu"
						value="${tongji.sxstu}" /></td>
					<td><input type="number" id="wgp"
						style="border-style:none;width:90px" name="tongji.wgp"
						value="${tongji.wgp}" /></td>
					<td><input type="number" id="shengbing"
						style="border-style:none;width:90px" name="tongji.shengbing"
						value="${tongji.shengbing}" /></td>
					<td><input type="number" id="youshi"
						style="border-style:none;width:90px" name="tongji.youshi"
						value="${tongji.youshi}" /></td>
					<td><input type="number" id="xtzx"
						style="border-style:none;width:90px" name="tongji.xtzx"
						value="${tongji.xtzx}" /></td>
					<td><input type="number" id="unconnect"
						style="border-style:none;width:90px" name="tongji.unconnect"
						value="${tongji.unconnect}" /></td>
					<td><input type="number" id="wfxtotal"
						style="border-style:none;width:90px" name="tongji.wfxtotal"
						value="${tongji.wfxtotal}" readonly="readonly" /></td>
					<td><input type="text" style="border-style:none;width:90px"
						name="tongji.tjr" value="${tongji.tjr}" readonly="readonly" /></td>
					<td><input type="text" style="border-style:none;width:90px"
						name="tongji.bzr" value="${tongji.bzr}" readonly="readonly" /></td>
				</tr>

			</table>

			</div>
			<br />
			<div style="margin:0 160px 0 0;float: right">
				<input type="button" class="btn" value="提交" style="width:50px;height:25px" />
			</div>
			<br /> <br />
		</form>
		<div style="width:960px;margin: 0 auto;">
			<p>
				<font size="+1">未返校合计人数不包括实习生数,返校生数+实习学生数+未返校学生数=学生总数</font>
			</p>
			<br />
		</div>
	</div>
	<script type="text/javascript">
		$(function() {
			//为返校统计
			var func = function() {
				var val = parseFloat($(‘#wgp‘).val())
						+ parseFloat($(‘#shengbing‘).val())
						+ parseFloat($(‘#youshi‘).val())
						+ parseFloat($(‘#xtzx‘).val())
						+ parseFloat($(‘#unconnect‘).val());
				$(‘#wfxtotal‘).val(val);
			};

			//自动改变输入框事件(未返校)
			$(‘#wgp,#shengbing,#youshi,#xtzx,#unconnect‘).change(func).keyup(
					func);
			//返校统计
			var sumzong = function() {
				var sumval = parseFloat($(‘#fxstu‘).val())
						+ parseFloat($(‘#sxstu‘).val())
						+ parseFloat($(‘#wfxtotal‘).val());
				$(‘#stunum‘).val(sumval);
			};
			$(
					‘#fxstu,#sxstu,#wfxtotal,#wgp,#shengbing,#youshi,#xtzx,#unconnect‘)
					.change(sumzong).keyup(sumzong);
		});
	</script>
	<script type="text/javascript">
		//JQuery防止退格键网页后退的实现代码
		$(document).keydown(
				function(e) {
					var doPrevent;
					if (e.keyCode == 8) {
						var d = e.srcElement || e.target;
						if (d.tagName.toUpperCase() == ‘INPUT‘
								|| d.tagName.toUpperCase() == ‘TEXTAREA‘) {
							doPrevent = d.readOnly || d.disabled;
						} else
							doPrevent = true;
					} else
						doPrevent = false;

					if (doPrevent)
						e.preventDefault();
				});
	</script>
	<script type="text/javascript">
        /* 提交结果,执行ajax */
        function btn(){
            var $btn = $("input.btn");//获取按钮元素
            
            //给按钮绑定点击事件
            $btn.bind("click",function(){
                $.ajax({
                    url:"saveCollegeAction",//saveCollegeAge  需要用来处理ajax请求的action,save为处理的方法名,CollegeAge为action名
                    type:"POST",
                    data:{//设置数据源
                    	stunum:$("#stunum").val(),
                    	fxstu:$("#fxstu").val(),//这里不要加","  不然会报错,而且根本不会提示错误地方
                    	sxstu:$("#sxstu").val(),
                    	wgp:$("#wgp").val(),
                    	shengbing:$("#shengbing").val(),
                    	youshi:$("#youshi").val(),
                    	xtzx:$("#xtzx").val(),
                    	unconnect:$("#unconnect").val(),
                    	wfxtotal:$("#wfxtotal").val()
                    },
                    dataType:"json",//设置需要返回的数据类型
                    success:function(data){
                        //得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来
                    	alert("更新成功!");
                        var d = eval("("+data.result+")");
                        $("#stunum").attr("value",""+d.stunuma+"");
                        $("#fxstu").attr("value",""+d.fxstua+"");
                        $("#sxstu").attr("value",""+d.sxstua+"");
                        $("#wgp").attr("value",""+d.wgpa+"");
                        $("#shengbing").attr("value",""+d.shengbinga+"");
                        $("#youshi").attr("value",""+d.youshia+"");
                        $("#xtzx").attr("value",""+d.xtzxa+"");
                        $("#unconnect").attr("value",""+d.unconnecta+"");
                        $("#wfxtotal").attr("value",""+d.wfxtotala+"");
                        //$("#stunum").text(""+d.stunuma+"");
                        
                    },
                    error:function(data){
                        alert("系统异常,请稍后重试!");
                    }//这里不要加","
                });
            });
        }
        /* 页面加载完成,绑定事件 */
        $(document).ready(function(){          
            btn();//点击提交,执行ajax
        });

    </script>
</body>
</html>

二、action页面----CollegeAction.java

这个是struts 分层中接收页面数据,并提交到 Dao类操作数据库的中间层

使用字段的get/set方法接手页面传值

package XXX.AAA.action;

import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import XXX.AAA.dao.CollegeDao;
import XXX.AAA.entity.Tongji;

import com.opensymphony.xwork2.Action;

public class CollegeAction implements Action {
	private Tongji tongji;
	//result 属性是用来ajax 返回结果集的,需要get/set方法
	private String result;
	public int stunum;
	private int fxstu;
	private int sxstu;
	private int wgp;
	private int shengbing;
	private int youshi;
	private int xtzx;
	private int unconnect;
	private int wfxtotal;

	@Override
	public String execute() throws Exception {
		return getCollege();
	}

	public String getCollege() {
		CollegeDao collegeDao = new CollegeDao();
		tongji = collegeDao.getCollege();
		return "success";
	}
	//ajax 更新数据
	public String save() {
	        //创建map集合,获取ajax 数据
		Map mapp = new HashMap();
		mapp.put("stunuma",stunum);
		mapp.put("fxstua",fxstu);
		mapp.put("sxstua",sxstu);
		mapp.put("wgpa",wgp);
		mapp.put("shengbinga",shengbing);
		mapp.put("youshia",youshi);
		mapp.put("xtzxa",xtzx);
		mapp.put("unconnecta",unconnect);
		mapp.put("wfxtotala",wfxtotal);
		if(ServletActionContext.getRequest().getSession().getAttribute("user")==null){
			return "success";
		}
		CollegeDao collegeDao = new CollegeDao();
		if (collegeDao.save(mapp) != 0) {
			//tongji = collegeDao.getCollege();
			//将map 解析到jason,方便数据返回
			JSONObject json = JSONObject.fromObject(mapp);
			result = json.toString();
			//System.out.println(result);
			return "success";
		}else{
			return "calcerror";
		}

	}

	public Tongji getTongji() {
		return tongji;
	}

	public void setTongji(Tongji tongji) {
		this.tongji = tongji;
	}
	//ajax
	public int getFxstu() {
		return fxstu;
	}
	public void setFxstu(int fxstu) {
		this.fxstu = fxstu;
	}

	public int getSxstu() {
		return sxstu;
	}
	public void setSxstu(int sxstu) {
		this.sxstu = sxstu;
	}
	public int getWgp() {
		return wgp;
	}
	public void setWgp(int wgp) {
		this.wgp = wgp;
	}
	public int getShengbing() {
		return shengbing;
	}
	public void setShengbing(int shengbing) {
		this.shengbing = shengbing;
	}
	public int getYoushi() {
		return youshi;
	}
	public void setYoushi(int youshi) {
		this.youshi = youshi;
	}
	public int getXtzx() {
		return xtzx;
	}
	public void setXtzx(int xtzx) {
		this.xtzx = xtzx;
	}
	public int getUnconnect() {
		return unconnect;
	}
	public void setUnconnect(int unconnect) {
		this.unconnect = unconnect;
	}
	public int getWfxtotal() {
		return wfxtotal;
	}
	public void setWfxtotal(int wfxtotal) {
		this.wfxtotal = wfxtotal;
	}
	public int getStunum() {
		return stunum;
	}
	public void setStunum(int stunum) {
		this.stunum = stunum;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}

}

对于数据解析成json,需要导入jar包,大家可以根据myecplise  控制台报的错,添加相应的jar包

下面列出所使用的jar包,应该很全了

struts核心包:

json需要的包:

三、dao页面----CollegeDao.java

操作数据库

public class CollegeDao extends BaseDao implements ParameterAware {

	 private HttpServletRequest request;

	public int save(Map mapp) {
		getConnection();
		int stunum = Integer.parseInt(mapp.get("stunuma").toString());
		int fxstu = Integer.parseInt(mapp.get("fxstua").toString());
		int sxstu = Integer.parseInt(mapp.get("sxstua").toString());
		int wgp = Integer.parseInt(mapp.get("wgpa").toString());
		int shengbing = Integer.parseInt(mapp.get("shengbinga").toString());
		int youshi = Integer.parseInt(mapp.get("youshia").toString());
		int xtzx = Integer.parseInt(mapp.get("xtzxa").toString());
		int unconnect = Integer.parseInt(mapp.get("unconnecta").toString());
		int wfxtotal = Integer.parseInt(mapp.get("wfxtotala").toString());
		//System.out.println(stunum);
		//System.out.println(fxstu);
		//System.out.println(sxstu);
		/*System.out.println(fxstu);
		System.out.println(stunum);
		System.out.println(stunum);
		System.out.println(stunum);
		System.out.println(stunum);*/
		if ((wgp + shengbing + youshi + xtzx + unconnect == wfxtotal)
				&& (fxstu + sxstu + wfxtotal == stunum)) {
			try {
				User user = (User) ActionContext.getContext().getSession()
						.get("user");
				pstm = conn
						.prepareStatement("update xy_tongji set stunum=?,fxstu=?,sxstu=?,"
								+ "wgp=?,shengbing=?,youshi=?,xtzx=?,unconnect=?, wfxtotal=?,"
								+ "tjr=?,bzr=? where nameid=?");
				pstm.setInt(1, stunum);
				pstm.setInt(2, fxstu);
				pstm.setInt(3, sxstu);
				pstm.setInt(4, wgp);
				pstm.setInt(5, shengbing);
				pstm.setInt(6, youshi);
				pstm.setInt(7, xtzx);
				pstm.setInt(8, unconnect);
				pstm.setInt(9, wfxtotal);
				pstm.setString(10, "");
				pstm.setString(11, "");
				pstm.setInt(12, user.getId());
				return pstm.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public void setParameters(Map<String, String[]> arg0) {
		// TODO Auto-generated method stub

	}
}

到此,ajax 成功

时间: 2024-08-27 17:55:39

struts2+jquery 实现ajax无刷新更新数据的相关文章

Struts2+Jquery+实现Ajax无刷新验证用户名是否存在

小弟之前一直搞不明白Struts2+Jquery+实现Ajax无刷新验证用户名该怎么弄,后来经过努力,终于搞定了,应注意struts配置文件的内容,好了直接上代码了 页面代码 <body> <s:form action="registAction" method="post" namespace="/user"> <table> <tr> <td>UserName</td>

使用AjaxPro实现无刷新更新数据

需求 在一个页面动态无刷新的更新后台得到的数据.要想无刷新的更新数据,需要使用Javascript能够获取后台返回的数据,然后通过第三方Javascript库(JQuery等)动态更新web页面DOM对应的数值即可,而AjaxPro库恰恰具有使用Javascript语句获取后台方法返回的数据的功能,问题就这样迎刃而解,顿时感觉萌萌哒. 流程 整个过程如下图所示: 详细操作 首先下载AjaxPro库(点击此处下载AjaxPro库),下载后解压得到两个dll文件,如下所示: 其中AjaxPro.2.

jquery 的ajax无刷新上传文件之后,页面还是会莫名的刷新-----解决办法

文件上传用到全局数组: $_FILES 只需要把下面的 <button onclick="post()">提交</button> 改为 <input type="button" onclick="post()" value="提交"/>就不会刷新页面了!!! 参考 http://bbs.csdn.net/topics/391852021 what fuck ... sb html   我在那

jQuery.form Ajax无刷新上传错误 (jQuery.handleError is not a function) 解决方案

今天,随着ajaxfileupload时间firebug财报显示,"jQuery.handleError is not a function"错误.因为一旦使用jQuery.form问题,我对照曾经的项目才发现,在这个项目中使用的jQuery是1.10.2的版本号,而曾经是使用的1.4.2.度娘一番之后,找到解决的方法:jQuery.handleError is not a function 报错原因是: handlerError仅仅在jquery-1.4.2之前的版本号中存在.jqu

jQuery.form Ajax无刷新上传报错 (jQuery.handleError is not a function) 解决办法

今天在用ajaxfileupload时firebug报了一个"jQuery.handleError is not a function"的错误.因为在以前使用jQuery.form一直都没有出现过这个问题,我对比以前的项目才发现,在这个项目中使用的jQuery是1.10.2的版本,而以前是使用的1.4.2.度娘一番之后,找到解决办法:jQuery.handleError is not a function 报错原因是: handlerError只在jquery-1.4.2之前的版本中存

window.history.pushState与ajax实现无刷新更新页面url

ajax能无刷新更新数据,但是不能更新url HTML5的新API: window.history.pushState, window.history.replaceState 用户操作history,点击前进后退按钮会触发popstate事件. 这些方法可以协同window.onpopstate事件一起工作. 改变url的demo 本页是foo.html,url改变成bar.html,内容却不变 <!DOCTYPE html> <html> <head> <me

Ajax无刷新(二)三级联动

1 写一个公用页面 2 <% 3 String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); 4 System.out.println(path); 5 request.setAttribute("path",path); 6 %> 1 其他页面需要绝对路径的话

使用Jquery的Ajax实现无刷新更新,修改,删除页面

原文:使用Jquery的Ajax实现无刷新更新,修改,删除页面 本文将向大家讲述一下最近工作的一些总结,主要包括了以下内容,注册界面以及详细信息界面的编辑.主要是介绍了AJAX技术,因为我觉得其他方面没什么好介绍的.首先是跟大家说一下Ajax的优点,假如你删除了一个页面的内容,你想当于点击了一个按钮,那么这个页面必然发生了回发事件,也就是说,你的页面必然被刷新了一次.以下是我从网上找来的一张Ajax的原理图,本人PS技术太差了,所以索性从网上找算了. 其实我个人对于Ajax技术的理解并没有上面图

学习aiax(javascript)--页面无刷新更新ajax更新时间

1.JSP代码 <%@ 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"