SpringMvc的簡單入門(五)之AJAX

一.什麼是AJAX

1.Ajax概念

 Ajax 是Web 開發一個流行的詞彙,全稱 Asynchronous JavaScript and XML(json,yml),異步的JavaScript和XML 。是幾種技術的強強聯合

2.Ajax如何工作

 Ajax(即異步 JavaScript 和 XML)是一種 Web 應用程序開發的手段,它採用客戶端腳本與Web 服務器交換數據。

3.爲什麼要學習Ajax

 使用Ajax的最大優點,就是能在不更新整個頁面的前提下維護數據。這使得Web應用程序更爲迅捷地迴應用戶動作,並避免了在網絡上發送那些沒有改變過的信息

二.json的應用

常用的幾種json:

1.阿里巴巴 fastjson

2.谷歌Gson

3.SpringMvc內嵌的JackSon

4.Json-lib

簡單的Json-lib Java應用

在pom.xml引入json-lib的架包

<!-- 引入json-lib的架包 -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
測試

package springmvc.less06.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
	/**注意
	 * json字符串的鍵 一定帶 "key":1
	 * 值數字不需要"" 字符串必須帶
	 */
	//將對象轉換成json{"username":"A","usid":1}
	public static void parseObject(){
		Map map= new HashMap();
		map.put("usid", 1);
		map.put("username", "A");
		//將Java轉換成json
		JSONObject jo=JSONObject.fromObject(map);
		System.out.println(jo.toString());
	}
	//{"username":"A","ma":{"stree":"gl","city":"sz"},"usid":1}
	public static void parsejsonArray(){
		Map map= new HashMap();
		map.put("usid", 1);
		map.put("username", "A");
	
		Map ma= new HashMap();
		ma.put("city", "sz");
		ma.put("stree", "gl");
		map.put("ma", ma);
		//將Java轉換成json
		JSONObject jo=JSONObject.fromObject(map);
		System.out.println(jo.toString());
	}
	//將數組轉換成json[{"username":"A","usid":1},{"username":"B","usid":2}]
	public static void parseAray(){
		Map map= new HashMap();
		map.put("usid", 1);
		map.put("username", "A");
		Map ma= new HashMap();
		ma.put("usid", 2);
		ma.put("username", "B");
		List list= new ArrayList();
		list.add(map);
		list.add(ma);
		//將Java數組轉換成json
		JSONArray ja=JSONArray.fromObject(list);
		System.out.println(ja.toString());
	}
	public static void main(String[] args) {
		parseAray();
	}
}

Js的json

<%@ 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 'list.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">
		function query(){
  			//無刷新調用http://..獲取到數據數據通過動dom方式添加到 table
  			//ajax(異步的ajax)+json
  			var xmlhttp=null;
  			//兼容所有的瀏覽器創建這個對象XHR對象
			if (window.XMLHttpRequest)
 			{// 支持code for IE7+, Firefox, Chrome, Opera, Safari
  				xmlhttp=new XMLHttpRequest();
 			}
			else
 			 {// code for IE6, IE5
 				 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 			 }
 			 //接收open產生的關聯,回調函數
  			xmlhttp.onreadystatechange=function()
 			 {
  				if (xmlhttp.readyState==4 && xmlhttp.status==200)
   				 {
   				 //返回的是字符串的json
  			 	 var resutJson=xmlhttp.responseText;
  			 	 //轉換爲接js對象
  			 	 var resutObj=JSON.parse(resutJson);
  			 	 	//獲取表格對象
  			 	 	var table=document.getElementById("myTable");
  			 	 	//將所有名字爲dataTr的tr全部刪除
  			 	 	var allDateTr=document.getElementsByName("dataTr");
  			 	 	 var length=allDateTr.length;
  			 	 	 for(var i=0;i<length;i++){
  			 	 	 	table.removeChild(allDateTr[0]);
  			 	 	 }
  			 	 	for(var i=0;i<resutObj.length;i++){
  			 	 		var obj=resutObj[i];
  			 	 		var tr=document.createElement("tr");
  			 	 		var td=document.createElement("td");
  			 	 		td.innerText=obj.foodname;
  			 	 		var td1=document.createElement("td");
  			 	 		td1.innerText=obj.price;
  			 	 		tr.setAttribute("name","dataTr");
  			 	 		//追加到table
  			 	 		tr.appendChild(td);
  			 	 		tr.appendChild(td1);
  			 	 		table.appendChild(tr);
  			 	 	}
   	 			}
  			}	//獲取文本框傳過來的值
  				var foodname=document.getElementsByName("foodname")[0].value;
  				//open表示產生一個請求的關聯(get提交)
				xmlhttp.open("GET","${pageContext.request.contextPath}/queryFood?foodname="+foodname,true);
				xmlhttp.send();
  		}
  	</script>
	</head>

	<body>
		<input type="text" name="foodname" />
		<input type="button" value="查詢" οnclick="query()"/>
		<table id="myTable">
			<tr><th>菜品名</th><th>菜品價格</th></tr>
		</table>

	</body>
</html>

servlet層

package springmvc.less06.dao;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MyFoodDaoImpl {
	@Autowired
	JdbcTemplate jdbc;
	//根據菜名查詢所有
	public List<Map<String,Object>> selectFood(String foodname){
		return jdbc.queryForList("select * from food where foodname like '%"+foodname+"%'");
		
	}
	//根據id刪除
	public void deleteFood(String foodid){
		jdbc.execute("delete from food where foodid ="+foodid);
	}
	//新增
	public void saveFood(String foodname,String price){
		jdbc.execute("insert into food(foodname,price) values('"+foodname+"','"+price+"')");
	}
	//修改
	public void updateFood(String foodid,String foodname,String price){
		jdbc.execute("update food set foodname='"+foodname+"',price='"+price+"' where foodid="+foodid);
	}
	
	
}

controller層

//自動裝配實現類
	@Autowired
	MyFoodDaoImpl mfi;
	//根據名稱查詢
	@RequestMapping(value="/queryFood",method=RequestMethod.GET)
	public String quer(String foodname,OutputStream os)throws Exception{
		//獲取所有數據
		List<Map<String,Object>> aur =mfi.selectFood(foodname);
		//轉換成json
		JSONArray array= JSONArray.fromObject(aur);
		String jst=array.toString();
		//輸出
		os.write(jst.getBytes("UTF-8"));
		return null;
	}

三.ajax的增刪改查

在mvc-servlet.xml中配置json消息轉換器

<!-- 將springmvc註解的action交給springmvc處理 國際化驗證需要配置validator-->
  <mvc:annotation-driven  validator="localValidatorFactoryBean">
  	<mvc:message-converters>
  	<!-- 配置json消息轉換器 -->
  		<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  			<property name="supportedMediaTypes">
  				<list>
  					<!-- 設置響應支持的類型 -->
  					<value>text/html</value>
  					<!-- 設置請求body支持的類型 -->
  					<value>application/x-www-form-urlencoded</value>
  				</list>
  			</property>
  		</bean>
  	</mvc:message-converters>
  </mvc:annotation-driven>

業務邏輯層

package springmvc.less06.dao;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MyFoodDaoImpl {
	@Autowired
	JdbcTemplate jdbc;
	//根據菜名查詢所有
	public List<Map<String,Object>> selectFood(String foodname){
		return jdbc.queryForList("select * from food where foodname like '%"+foodname+"%'");
		
	}
	//根據id刪除
	public void deleteFood(String foodid){
		jdbc.execute("delete from food where foodid ="+foodid);
	}
	//新增
	public void saveFood(String foodname,String price){
		jdbc.execute("insert into food(foodname,price) values('"+foodname+"','"+price+"')");
	}
	//修改
	public void updateFood(String foodid,String foodname,String price){
		jdbc.execute("update food set foodname='"+foodname+"',price='"+price+"' where foodid="+foodid);
	}
	
	
}

controller層

package springmvc.less06.controller;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import springmvc.less06.dao.MyFoodDaoImpl;
@Controller
public class MyFoodController {
	//自動裝配實現類
	@Autowired
	MyFoodDaoImpl mfi;
	//根據名稱查詢
	@RequestMapping(value="/queryFood",method=RequestMethod.GET)
	public String quer(String foodname,OutputStream os)throws Exception{
		//獲取所有數據
		List<Map<String,Object>> aur =mfi.selectFood(foodname);
		//轉換成json
		JSONArray array= JSONArray.fromObject(aur);
		String jst=array.toString();
		//輸出
		os.write(jst.getBytes("UTF-8"));
		return null;
	}
	/**
	 * 返回字節數組+@ResponseBody
	 * @param foodname
	 * @param os
	 * @return
	 * @throws Exception
	 */
	//根據菜名查詢
	@ResponseBody
	@RequestMapping(value="/queryFoodre",method=RequestMethod.GET)
	public byte[] querFood(String foodname,OutputStream os)throws Exception{
		List<Map<String,Object>> aur =mfi.selectFood(foodname);
		JSONArray array= JSONArray.fromObject(aur);
		String jst=array.toString();
		return jst.getBytes("UTF-8");
		
	}
	/**
	 * 直接返回對象Spring解析json
	 * 
	 * @param foodname
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryFoodreturn",method=RequestMethod.GET)
	public List<Map<String,Object>> querFoode(String foodname)throws Exception{
		List<Map<String,Object>> aur =mfi.selectFood(foodname);
		return aur;
		
	}
	//根據id刪除
	@RequestMapping(value="/food/{foodid}",method={RequestMethod.DELETE})
	public String deleteFood(@PathVariable String foodid,OutputStream os) throws Exception{
		try{
			mfi.deleteFood(foodid);
			os.write("1".getBytes("UTF-8"));
		}catch(Exception e){
			os.write("0".getBytes("UTF-8"));
		}
		return null;
	}
	//修改
	@RequestMapping(value="/food/{foodId}",method={RequestMethod.PUT})
	public String updateFood(@PathVariable String foodId,String foodname,String price,OutputStream os) throws Exception{
		try {
			mfi.updateFood(foodId, foodname, price);
			os.write("1".getBytes("UTF-8"));
		} catch (Exception e) {
			os.write("0".getBytes("UTF-8"));
		}
		return null;
	}
	//新增
	@RequestMapping(value="/food",method={RequestMethod.POST})
	public String saveFood(String foodname,String price,OutputStream os) throws Exception{
		try{
			mfi.saveFood(foodname, price);
			os.write("1".getBytes("UTF-8"));
		}catch(Exception e){
			os.write("0".getBytes("UTF-8"));
		}
		return null;
	}
	
}

視圖層

<%@ 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 'list.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">
/*
 封裝的發送ajax的函數 
 *url 發送請求的地址
 *方法類型  get或者post
 *參數  通過 鍵=值&鍵=值 方式
 *回調函數 當結果返回後 自動調用的函數 第一個參數就是返回的結果
  function(responseText){
     	具體的邏輯(頁面渲染)
  }
*/		
/*
  使用ajax
   儘量使用 true 異步模式  (防假死)
    儘量將獲取數據之後的邏輯處理(頁面渲染)放在回調函數中
*/	
function sendAjax(url,methodType,param,retnFunction){
	//無刷新調用 http://localhost:8080/s/queryFood 獲取到數據 數據通過dom方式添加到 table中
	//ajax(異步的ajax)+json
	var xmlhttp=null;
	//兼容所有的瀏覽器創建這個對象 XHR對象
	if (window.XMLHttpRequest) {//支持 code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	//回調函數 當請求發送後 收到結果自動調用該方法
	xmlhttp.onreadystatechange = function() {
	    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
	       //返回的json
	       retnFunction(xmlhttp.responseText)
	    }
    }
	if(methodType=="get" || methodType=="GET" ){
		//open方法表示產生一個請求的關聯(Get 提交)
	  xmlhttp.open("GET", url+"?"+param, true);
	  //提交
	  xmlhttp.send();
	}else{
	/**一個AJAX線程是否執行完成可以通過回調函數xmlhttp.onreadystatechange 是否執行完成來判斷
		異步 多個線程同事執行 無法判斷誰先執行 true
		同步 一次只允許一個線程執行 false 頁面會假死
	*/
	  xmlhttp.open("POST", url, true);
	  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
	  xmlhttp.send(param);
	}
}				
function query() {
	//獲取文本框傳過來的值
     var foodname=document.getElementsByName("foodName")[0].value;
     sendAjax("${pageContext.request.contextPath}/queryFood","GET","foodname="+foodname,function(responseText){
            //返回的是字符串的json
			var resutlJson = responseText;
			var resultObj=JSON.parse(resutlJson);
			//獲取表格對象
			var table=document.getElementById("myTable");
			//將所有名字爲 dataTr的tr全部刪除 
			var allDataTr=document.getElementsByName("dataTr");
			var length=allDataTr.length;
			for(var i=0;i<length;i++){
			  table.removeChild(allDataTr[0]);
			}
			//根據json的行數追加多個tr
			for(var i=0;i<resultObj.length;i++){
			   var obj=resultObj[i];
			   var td=document.createElement("td");
			   td.innerText=obj.foodname;
			   var td1=document.createElement("td");
			   td1.innerText=obj.price;
			   
			   var td2=document.createElement("td");
			   //刪除按鈕
			   var ib=document.createElement("button");
			   ib.innerText="X";
			   //
			   var ib1=document.createElement("button");
			   ib1.innerText="U";
			   td2.appendChild(ib);
			   td2.appendChild(ib1);
			   var tr=document.createElement("tr");
			   //將當前行的json對象綁定到當前按鈕上
			   ib.foodObj=obj;
			   //將當前行的tr綁定到當前按鈕上
			   ib.myLineTr=tr;
			   //刪除按鈕事件
			   ib.addEventListener("click",function(){
			      //獲取當前按鈕
			      var eventSrc=event.srcElement;
			      //刪除當前行  + 發送ajax請求到後臺 刪除數據庫
			      table.removeChild(eventSrc.myLineTr);
			      sendAjax("${pageContext.request.contextPath}/food/"+ib.foodObj.foodid,"POST","_method=delete",function(responseText){
			         if(responseText==1)
			            alert("刪除成功");
			         else{
			            alert("刪除失敗");
			         }
			      });
			   });
			   ib1.foodObj=obj;
			   ib1.addEventListener("click",function(){
			       var eventSrc=event.srcElement;
			       document.getElementById('updateDiv').style.display='block';
			       document.getElementsByName("umyFoodName")[0].value=eventSrc.foodObj.foodname;
			       document.getElementsByName("umyFoodPrice")[0].value=eventSrc.foodObj.price;
			       document.getElementsByName("umyFoodId")[0].value=eventSrc.foodObj.foodid;
			   })
			   tr.setAttribute("name","dataTr");
			  	//追加到tr
			   tr.appendChild(td);
			   tr.appendChild(td1);
			   tr.appendChild(td2);
			   //追加到table
			   table.appendChild(tr);
			}
     })
}
/**
  新增的方法
**/
function saveFood(){
   var myFoodName=document.getElementsByName("myFoodName")[0].value;
   var myFoodPrice=document.getElementsByName("myFoodPrice")[0].value;
   sendAjax("${pageContext.request.contextPath}/food","POST","foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
			         if(responseText==1){
			            document.getElementById('addDiv').style.display='none';
			            query();
			            alert("新增成功");
			         }else{
			            alert("新增失敗");
			         }
	});
}

/**
  修改的方法
**/
function updateFood(){
   var myFoodName=document.getElementsByName("umyFoodName")[0].value;
   var myFoodPrice=document.getElementsByName("umyFoodPrice")[0].value;
   var myFoodId=document.getElementsByName("umyFoodId")[0].value;
   sendAjax("${pageContext.request.contextPath}/food/"+myFoodId,"POST","_method=put&foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
			         if(responseText==1){
			            document.getElementById('updateDiv').style.display='none';
			            query();
			            alert("修改成功");
			            
			         }else{
			            alert("修改失敗");
			         }
	});
   
   
}

</script>
	</head>

	<body>
		<input type='text' name="foodName" />
		<input type='button' value="查詢" οnclick="query()"><input type='button' value="新增" οnclick="document.getElementById('addDiv').style.display='block';">
		<table id="myTable">  
           <tr><th>菜品名</th><th>菜品價格</th><th>操作</th></tr>
		</table>
	</body>
	
	<div id="addDiv" style="display:none;position: absolute;left:40%;top:40%;z-index: 100;border:1px solid black; width:250px;height:100px ">
	 
	 菜品名:<input type="text" name="myFoodName"><br/>
	 價   格:<input type="text" name="myFoodPrice"><br/>
	 <input type="button" value="保存" οnclick="saveFood()">   <input type="button" value="關閉" οnclick="document.getElementById('addDiv').style.display='none';" ><br/>
	</div>
	
	
	<div id="updateDiv" style="display:none;position: absolute;left:40%;top:40%;z-index: 100;border:1px solid black; width:250px;height:100px ">
	 <input type="hidden" name="umyFoodId" >
	 菜品名:<input type="text" name="umyFoodName"><br/>
	 價   格:<input type="text" name="umyFoodPrice"><br/>
	 <input type="button" value="修改" οnclick="updateFood()">   <input type="button" value="關閉" οnclick="document.getElementById('updateDiv').style.display='none';" ><br/>
	</div>
	
	
</html>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章