struts2+jquery 實現ajax無刷新更新數據

前幾天爲了實現一個struts 的 ajax無刷新更新數據的例子,發現網上資料不多,不少已通過時或者連接都失效了javascript

不過整合他們的資料,加上本身的研究,終於實現了效果css

要求:一、各個學院提交學生數據到服務器,要求ajax 無刷新更新數據,html

          二、服務器端返回「更新成功」的提示窗口;java

          三、以後,使用jquery 更新input輸入框的value值,爲實現jquery 打印頁面局部數據作準備。jquery

此處使用struts2的第二種方法,(修改struts 配置文件,增長ajax package 的方式實現)ajax

1、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>

2、action頁面----CollegeAction.javaapache

這個是struts 分層中接收頁面數據,並提交到 Dao類操做數據庫的中間層json

使用字段的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須要的包:

3、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 成功

相關文章
相關標籤/搜索