1. 程式人生 > >struts+ajax+jquery:實現異步新增數據

struts+ajax+jquery:實現異步新增數據

sim orm html 沖突 lin itl nac 處理 ajax請求

很久未有更新,最近因為團隊其它事耽誤沒有繼續學習,但心中十分忐忑不安,抽空把自己薄弱的點拿來再鞏固一下!

本身異步刷新用處非常多,SSH框架對我來講,已無難度,但結合ajax處理一些增刪查改分頁等,就覺得無奈,還是把基礎抓起來先

先看一下本次功能的效果圖:

技術分享

1、用到的jar包

下載地址:http://pan.baidu.com/s/1hspDeoW

2、index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘index.jsp‘ starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
	<script type="text/javascript">
		//提交結果,執行ajax
		function btn(){
			var $btn = $("input.btn");//獲取按扭元素
			
			//給按扭綁定點擊事件
			$btn.bind("click",function(){
				$.ajax({
					type:"post",
					url:"jsonAction.action",//需要用來處理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){
						alert(data);
						var d = eval("("+data+")");//將數據轉換成json類型,可以把data用alert()輸出來看看是什麽樣的結構,得到的是一個形如{"key":"value","key1":"value1"}的數據類型,然後取舍出來
						//來一條增加一條tr 3列td
						var tr_begin = "<tr>";
						var tr_end = "</tr>";
						var td_c1="<td>"+d.name+"</td>";
						var td_c2="<td>"+d.age+"</td>";
						var td_c3="<td>"+d.position+"</td>";
						var text = tr_begin+td_c1+td_c2+td_c3+tr_end;
						$("#view").append(text);
					},
					error:function(){
						alert("系統異常,請稍後再試!");
					}//這裏不用加","
				});
			
			});
		}
		
		//頁面加載完成,觸發綁定事件
		$(document).ready(function(){
			btn();//點擊提交,執行ajax
		});
	
	</script>
  </head>
  
  <body>
    

	<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> -->
		
		<table id="view">
			<tr>
				<td>姓名</td>
				<td>年紀</td>
				<td>職務</td>
			</tr>
		</table>
	</div>
	
	<div id="authorgraph"><img  src=""></div>
  </body>
</html>

  

3、後端action

package 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 org.apache.struts2.json.JSONUtil;

import sun.org.mozilla.javascript.internal.json.JsonParser;

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 String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
		
	}
	
	/**
	 * 處理ajax請求
	 */
	public String executeAjax(){
		try {
			//獲取數據
			String name = request.getParameter("name");
			int age = Integer.parseInt(request.getParameter("age"));
			String position = request.getParameter("position");
			
			System.out.println("name=="+name+"age=="+age+"position=="+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賦值,傳遞給頁面
			System.out.println("result==="+result);
		} catch (Exception e) {
			e.printStackTrace();
		}return SUCCESS;
	}
	
}

  4、struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

	<constant name="struts.i18n.encoding" value="UTF-8"></constant>
	
	<package name="simpleton" extends="struts-default,json-default">
		<action name="jsonAction" method="executeAjax" class="action.JsonAction">
			<!-- 返回json類型數據 -->
			<result type="json">
				<param name="root">result</param><!-- result是action中設置的變量名,也是頁面需要返回的數據,該變量必須有setter和getter方法 -->
				
			</result>
		</action>
	
	</package>
</struts>    

  

總結:過程中我遇到jar包缺少的問題,關於lang包的版本問題,我放了2個,沒有沖突,滿足了要求。

java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils

struts+ajax+jquery:實現異步新增數據