1. 程式人生 > 實用技巧 >07-開發環境基本配置

07-開發環境基本配置

Ajax

2020/9/3 17:40:34


Ajax簡介

一種用於網頁非同步請求的技術 ,  用於與伺服器進行非同步互動 , 以及 區域性網頁的重新整理.

ajax的GET請求使用步驟

1.	建立一個用於非同步請求的物件
	var xhr = new XMLHttpRequest();

2.	設定請求的方式 以及請求地址
	xhr.open("GET","地址?引數列表");

3.	設定請求結果產生時 的 處理函式 
	(此函式在一次	請求中會執行多次 , 當請求狀態每改變一次, 則觸發一次)
	xhr.onreadystatechange = function(){
		4.	獲取請求狀態碼, 根據狀態碼判斷請求到了哪一步.
			if(xhr.readyState == 4){
				5.	判斷響應的狀態碼 (404資源找不到 , 500伺服器內部錯誤 , 200成功 等等)
				if(xhr.status == 200){
					6.	獲取到響應體(xhr.responseText)
				}else{
					//錯誤的提示
				}
			}
	}

7.	將請求傳送
	xhr.send();


Ajax的POST請求使用步驟 ***

	1.	建立一個用於非同步請求的物件
		var xhr = new XMLHttpRequest();
	2.	設定請求的方式 以及請求地址
		xhr.open("POST","地址");
	3.	設定請求結果產生時 的 處理函式 
		(此函式在一次	請求中會執行多次 , 當請求狀態每改變一次, 則觸發一次)
		xhr.onreadystatechange = function(){
			4.	獲取請求狀態碼, 根據狀態碼判斷請求到了哪一步.
				if(xhr.readyState == 4){
					5.	判斷響應的狀態碼 (404資源找不到 , 500伺服器內部錯誤 , 200成功 等等)
					if(xhr.status == 200){
						6.	獲取到響應體(xhr.responseText)
					}else{
						//錯誤的提示
					}
				}
		}

	7.	設定請求頭部
		xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");

	8.	將請求傳送 (引數列表格式: 與GET請求?後的格式一致)
		xhr.send(引數列表);

注意:
	xhr.readyState	:
		表示請求狀態 , 值:
			0	:	請求初始化中
			1	:	請求正在傳送
			2	:	請求傳送完畢
			3	:	伺服器開始響應
			4	:	響應完畢 ,連線已斷開, 回覆的內容已經得到了

Ajax跨域實現

在servlet的程式碼中, 在響應之前加入如下兩行程式碼, 即可實現:

	response.addHeader("Access-Control-Allow-Origin","*");
	response.addHeader("Access-Control-Allow-Methods","GET,POST");	

通過GSON.jar 更快速的生成JSON格式字串 .

步驟:
	1.	引入jar檔案
	2.	在需要將物件轉為JSON字串的位置, 加入如下格式程式碼即可:
		String json = new Gson().toJSON(物件);

物件:
	String json2 = new Gson().toJson(u);

集合:
	ArrayList<User30> data = new ArrayList<>();
	for(int i=0;i<100;i++) {
		User30 u = new User30(1001+i, "dsg"+i, "123"+i);
		data.add(u);
	}
	
	String json = new Gson().toJson(data);
	System.out.println(json);

通過GSON.jar 將JSON格式字串, 轉換為物件, 並取出其中屬性.

前提條件:
	1.	JSON格式的字串, 格式必須正確.
	2.	JSON字串中的屬性 必須要與 準備轉換型別屬性 一致.

	例如:	
		要將如下字串轉換為物件 , 必須存在屬性匹配的類, 例如:
			字串:
				{
					"name":"xxx",
					"age":18
				}
			類:
				class 類名{
					private String name;
					private int age;
					get/set...
				}

格式:
	1.	引入Jar包
	2.	在需要轉換的位置, 加入如下程式碼:
			物件名 = new Gson().fromJson(JSON字串,物件型別.class);

案例:
	String json = "{\"id\":10001,\"username\":\"zhangsan\",\"password\":\"123456\"}";
	User30 u = new Gson().fromJson(json, User30.class);
	System.out.println(u.getUsername());

通過GSON.jar 將JSON資料, 轉換為集合

Map:
	Map<String,Object> map = new Gson().fromJson(JSON字串,Map.class);

List 
	List<Object> list = new Gson().fromJson(JSON字串,List.class);	

ajax-Jquery

Jquery對ajax操作進行了封裝 , 簡化了ajax開發的流程 .實現了多瀏覽器的相容.

ajax函式

	函式名稱:	$.ajax
	引數列表:	長度為1 , 需要傳遞一個物件.

	通常傳遞到引數1的物件,  我們使用JSON格式傳輸, 屬性與值描述如下:
		{
			url:"請求的地址",
			type:"請求方式GET/POST...",
			async:"預設true,表示非同步請求",
			data:"請求的引數,格式與網址?後的格式一致",
			dataType:"TEXT/JSON",//表示伺服器返回的資料型別.如果編寫JSON , 我們接收到的資料 就是一個物件
			success:function(data){
				//當伺服器請求成功時, 這裡執行
				//引數data就是響應的內容.
				//	當dataType的值為TEXT時,  data是一個string型別的資料
				//	當dataType的值為JSON時,  data是一個物件.
			},
			error:function(){
				//當伺服器返回的狀態碼不再200-299的範圍 , 則表示失敗, 這裡執行
			}
		}

get函式與post函式

兩個函式的格式, 完全一致, 一個用於GET請求, 一個用於POST請求.

	函式名稱:	$.get     $.post
	引數列表:
			列表長度為4:
			引數1.	url	:	請求地址
			引數2.	data:	請求時攜帶的引數 , 與網址?後的引數格式一致.
			引數3.	success:	當請求成功時 , 處理的函式
			引數4.	響應的資料型別:	TEXT/JSON

	格式示例:
		$.get("s1.do","",function(data){

		},"JSON");

getJSON函式

	函式名稱:	$.getJSON
	引數列表:
			引數列表長度為3
			引數1.	url	:	請求地址
			引數2.	data:	請求時攜帶的引數, 與網頁?後的引數格式一致
			引數3.	success:	當請求成功時, 處理的函式.

	案例:
		<h3>快遞查詢2</h3>
		<input placeholder="請輸入快遞單號"><button onclick="x1()">查詢</button>
		<script type="text/javascript">
			function x1(){
				$("#ul1").html("");
				//1.	得到使用者輸入的快遞單號
				var number = $("input").val();
				//2.	傳送ajax請求
				layer.msg("拼命查詢中...",{icon:16,shade:0.01});
				$.getJSON("s2.do","number="+number,function(data){
					if(data.status == 0){
						//查詢成功
						var arr = data.result.list;
						for(var i=0;i<arr.length;i++){
							var $li = $("<li>時間:"+arr[i].time+"<br>進度:"+arr[i].status+"</li>");
							$("#ul1").append($li);
						}
					}else{
						//查詢失敗
						layer.msg("很遺憾, 查詢失敗了");
					}
				});
			}
		</script>
		<ul id="ul1">
		
		</ul>


load函式 熟悉

	與其他的ajax函式不同, 它是使用jquery物件呼叫的. 
	作用是 , 將一個網址的響應體, 載入到呼叫方法的元素內部.


	函式名稱: $obj.load
	引數列表:
			引數列表長度為3
			引數1.	url	:	請求地址
			引數2.	[data]:	傳遞的引數
			引數3.	[success]:	請求成功時的處理函式.

	案例:
	<style type="text/css">
		#content{
			width:1170px;
			margin: 0 auto;
			text-align: center;
		}
		.item{
			width:200px;
			text-align: center;
			height:300px;
			line-height: 300px;
			border:2px solid #999;
			box-shadow:0px 0px 3px 2px #aaa;
			display: inline-block;
			margin: 10px;
		}
	</style>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="layer/layer.js"></script>
	</head>
	<body>
	<h3>JD商品</h3>
		<script type="text/javascript">
			//表示當前頁數
			var count = 1;
			function x1(i){
				if(count==1 && i==-1){
					layer.msg("已經是第一頁了");
					return;
				}
				count+=i;
				//發起ajax, 請求頁面.得到新的商品內容
				$("#content").load("page.jsp","count="+count);
				$("#count").html(count);
			}
		</script>
		
		
		<div>
			<button onclick="x1(-1)">上一頁</button>
			<span id="count">1</span>
			<button onclick="x1(1)">下一頁</button>
		</div>
		<div id="content">
			<div class="item">
				商品1 ,圖片請自行腦補
			</div>
			<div class="item">
				商品2 ,圖片請自行腦補
			</div>
			<div class="item">
				商品3 ,圖片請自行腦補
			</div>
			<div class="item">
				商品4 ,圖片請自行腦補
			</div>
			<div class="item">
				商品5 ,圖片請自行腦補
			</div>
			<div class="item">
				商品6 ,圖片請自行腦補
			</div>
			<div class="item">
				商品7 ,圖片請自行腦補
			</div>
			<div class="item">
				商品8 ,圖片請自行腦補
			</div>
			<div class="item">
				商品9,圖片請自行腦補
			</div>
			<div class="item">
				商品10 ,圖片請自行腦補
			</div>
		
		</div>
	</body>

ajax-Vue

除了需要引入vue.js檔案以外, 還需要引入: vue-resource.js

基於全域性的  Ajax

	GET請求格式:
		Vue.http.get("請求地址",[傳遞的引數]).then(success,error);

	POST請求格式:
		Vue.http.post("請求地址",[傳遞的引數],{"emulateJSON":true}).then(success,error);


在Vue例項中使用的ajax

	GET請求格式:
		this.$http.get("請求地址",[傳遞的引數]).then(success,error);

	POST請求格式:
		this.$http.post("請求地址",[傳遞的引數],{"emulateJSON":true}).then(success,error);

GET請求引數傳遞的格式

	{params:{鍵1:值1,鍵2:值2...鍵n:值n}}

POST請求引數傳遞的格式

	{鍵1:值1,鍵2:值2...鍵n:值n}
success函式 與 error函式 :
這兩個函式都存在一個引數: response , 指的是響應物件.

響應物件的屬性:
	1.	url	:	請求的網址
	2.	body:	伺服器返回的響應體, 如果是JSON格式, 則body為物件, 如果不是JSON格式 ,則body為string
	3.	ok	:	boolean值, 如果響應碼為200-299之間 值為true , 表示成功.
	4.	status:	伺服器響應的狀態碼 ,例如: 200 , 404 ,500 ...
	5.	statusText: 響應狀態碼對應的文字, 例如status==200時, 則statusText=ok.
	
響應物件的函式:
	1.	text()	:	以字串形式, 返回響應體.
	2.	json()	:	以物件形式, 返回響應體.
	3.	blob()	:	以二進位制Blob物件形式, 返回相應內容

Vue ajax 案例1 . 全域性GET

<h3>天氣查詢</h3>
<input id="input1" placeholder="請輸入查詢的城市"><button onclick="x1()">查詢</button>
<div id="div1"></div>
<script type="text/javascript">
	function x1(){
		var div1 = document.getElementById("div1");
		div1.innerHTML = "";
		var city = document.getElementById("input1").value;
		//s3.do?city=輸入框內容
		Vue.http.get("s3.do",{params:{"city":city}}).then(function(res){
			var date = res.body.result.date;
			var week = res.body.result.week;
			var weather = res.body.result.weather;
			var temp = res.body.result.temp;
			var templow = res.body.result.templow;
			var temphigh = res.body.result.temphigh;
			div1.innerHTML = 
			"日期:"+date+"&nbsp;&nbsp;&nbsp;"+week+"<br><br>"
			+"天氣情況:"+weather
			+"<br>當前溫度:"+temp+"<br>"
			+"今天溫度區間: "+templow+" ~ "+temphigh;
			;
			
		},function(res){
			div1.innerHTML = "很遺憾, 查詢失敗";
		});
	}
</script>

Vue ajax 案例2 . 全域性POST

<h3>天氣查詢</h3>
<input id="input1" placeholder="請輸入查詢的城市"><button onclick="x1()">查詢</button>
<div id="div1"></div>
<script type="text/javascript">
	function x1(){
		var div1 = document.getElementById("div1");
		div1.innerHTML = "";
		var city = document.getElementById("input1").value;
		//s3.do?city=輸入框內容
		Vue.http.post("s3.do",{"city":city},{"emulateJSON":true}).then(function(res){
			var date = res.body.result.date;
			var week = res.body.result.week;
			var weather = res.body.result.weather;
			var temp = res.body.result.temp;
			var templow = res.body.result.templow;
			var temphigh = res.body.result.temphigh;
			div1.innerHTML = 
			"日期:"+date+"&nbsp;&nbsp;&nbsp;"+week+"<br><br>"
			+"天氣情況:"+weather
			+"<br>當前溫度:"+temp+"<br>"
			+"今天溫度區間: "+templow+" ~ "+temphigh;
			;
			
		},function(res){
			div1.innerHTML = "很遺憾, 查詢失敗";
		});
	}
</script>

Vue ajax 案例3 . Vue例項中GET

<h3>天氣查詢</h3>
<div id="main">
	<input id="input1" placeholder="請輸入查詢的城市" v-model="city"><button @click="x1">查詢</button>
	<div><br><br>
		日期:{{time}}&nbsp;&nbsp;&nbsp;&nbsp;{{week}}<br><br>
		天氣:{{weather}}<br>
		當前溫度:{{temp}}<br>
		當天溫度區間:{{templow}} ~ {{temphigh}}<br>
	</div>

</div>
<script type="text/javascript">
	var vue = new Vue({
		el:"#main",
		data:{
			city:"",
			time:"",
			week:"",
			weather:"",
			temp:"",
			templow:"",
			temphigh:"",
		},
		methods:{
			x1:function(){
				this.$http.get("s3.do",{params:{"city":this.city}}).then(function(res){
					this.time = res.body.result.date;
					this.week = res.body.result.week;
					this.weather = res.body.result.weather;
					this.temp = res.body.result.temp;
					this.templow = res.body.result.templow;
					this.temphigh = res.body.result.temphigh;
				},function(res){
					
				});
			}
		}
	});
</script>

Vue ajax 案例4 . Vue例項中POST

<h3>天氣查詢</h3>
<div id="main">
	<input id="input1" placeholder="請輸入查詢的城市" v-model="city"><button @click="x1">查詢</button>
	<div><br><br>
		日期:{{time}}&nbsp;&nbsp;&nbsp;&nbsp;{{week}}<br><br>
		天氣:{{weather}}<br>
		當前溫度:{{temp}}<br>
		當天溫度區間:{{templow}} ~ {{temphigh}}<br>
	</div>

</div>
<script type="text/javascript">
	var vue = new Vue({
		el:"#main",
		data:{
			city:"",
			time:"",
			week:"",
			weather:"",
			temp:"",
			templow:"",
			temphigh:"",
		},
		methods:{
			x1:function(){
				this.$http.post("s3.do",{"city":this.city},{"emulateJSON":true}).then(function(res){
					this.time = res.body.result.date;
A					this.week = res.body.result.week;
					this.weather = res.body.result.weather;
					this.temp = res.body.result.temp;
					this.templow = res.body.result.templow;
					this.temphigh = res.body.result.temphigh;
				},function(res){
					
				});
			}
		}
	});
</script>