Ajax技術

一、Ajax概述

1.什麼是同步,什麼是異步

同步現象:客戶端發送請求到服務器端,當服務器返回響應之前,客戶端都處於等待卡死狀態

異步現象:客戶端發送請求到服務器端,無論服務器是否返回響應,客戶端都可以隨意做其他事情,不會被卡死

 

2.Ajax的運行原理

頁面發起請求,會將請求發送給瀏覽器內核中的Ajax引擎,Ajax引擎會提交請求到服務器端,在這段時間裏,客戶端可以任意進行任意操作,直到服務器端將數據返回給Ajax引擎後,會觸發你設置的事件,從而執行自定義的js邏輯代碼完成某種頁面功能。

 

 

二、js原生的Ajax技術(瞭解)

js原生的Ajax其實就是圍繞瀏覽器內內置的Ajax引擎對象進行學習的,要使用js原生的Ajax完成異步操作,有如下幾個步驟:

1)創建Ajax引擎對象

2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎)

3)綁定提交地址

4)發送請求

5)接受響應數據

//1、創建ajax引擎對象 ---- 所有的操作都是通過引擎對象
var xmlHttp = new XMLHttpRequest();
//2、綁定監聽 ---- 監聽服務器是否已經返回相應數據
xmlHttp.onreadystatechange = function(){
	if(xmlHttp.readyState==4&&xmlHttp.status==200){
		//5、接受相應數據
		var res = xmlHttp.responseText;
		document.getElementById("span2").innerHTML = res;
	}
}
//3、綁定地址
xmlHttp.open("POST","/WEB22/ajaxServlet",false);
//4、發送請求
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("name=wangwu");

注意:如果是post提交

在發送請求之前設置一個頭

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

總結:

所有異步訪問都是ajax引擎

 

 

三、Jquery的Ajax技術(重點)

jquery是一個優秀的js框架,自然對js原生的ajax進行了封裝,封裝後的ajax的操作方法更簡潔,功能更強大,與ajax操作相關的jquery方法有如下幾種,但開發中經常使用的有三種;

1)$.get(url, [data], [callback], [type])

2)$.post(url, [data], [callback], [type])

 

其中:

url:代表請求的服務器端地址

data:代表請求服務器端的數據(可以是key=value形式也可以是json格式)

callback:表示服務器端成功響應所觸發的函數(只有正常成功返回才執行)

type:表示服務器端返回的數據類型(jquery會根據指定的類型自動類型轉換)

常用的返回類型:text、json、html等

function fn1(){
	//get異步訪問
	$.get(
		"/WEB22/ajaxServlet2", //url地址
		{"name":"張三","age":25}, //請求參數
		function(data){ //執行成功後的回調函數
			//{"name":"tom","age":21}
			alert(data.name);
		},
		"json"
	);
}
function fn2(){
	//post異步訪問
	$.post(
		"/WEB22/ajaxServlet2", //url地址
		{"name":"李四","age":25}, //請求參數
		function(data){ //執行成功後的回調函數
			alert(data.name);
		},
		"json"
	);
}

 

3)$.ajax( { option1:value1,option2:value2... } );

常用的option有如下:

async:是否異步,默認是true代表異步

data:發送到服務器的參數,建議使用json格式

dataType:服務器端返回的數據類型,常用text和json

success:成功響應執行的函數,對應的類型是function類型

type:請求方式,POST/GET

url:請求服務器端地址

function fn3(){
	$.ajax({
		url:"/WEB22/ajaxServlet2",
		async:true,
		type:"POST",
		data:{"name":"lucy","age":18},
		success:function(data){
			alert(data.name);
		},
		error:function(){
			alert("請求失敗");
		},
		dataType:"json"
	});
}



四、案例實現

 1、異步校驗用戶名是否存在

<script type="text/javascript">
	$(function(){
		
		//爲輸入框綁定事件
		$("#username").blur(function(){
			//1、失去焦點獲得輸入框的內容
			var usernameInput = $(this).val();
			//2、去服務端校驗該用戶名是否存在---ajax
			$.post(
				"${pageContext.request.contextPath}/checkUsername",
				{"username":usernameInput},
				function(data){
					var isExist = data.isExist;
					//3、根據返回的isExist動態的顯示信息
					var usernameInfo = "";
					if(isExist){
						//該用戶存在
						usernameInfo = "該用戶名已經存在";
						$("#usernameInfo").css("color","red");
					}else{
						usernameInfo = "該用戶可以使用"
						$("#usernameInfo").css("color","green");
					}
					$("#usernameInfo").html(usernameInfo);
					
				},
				"json"
			);
			
			
		});

		
	});
</script>
<div class="col-sm-6">
	<input type="text" class="form-control" id="username"
		placeholder="請輸入用戶名">
	<span id="usernameInfo"></span>
</div>
//獲得要校驗的用戶名
String username = request.getParameter("username");
//傳遞username到service
UserService service = new UserService();
boolean isExist = false;
try {
	isExist = service.checkUsername(username);
} catch (SQLException e) {
	e.printStackTrace();
}

response.getWriter().write("{\"isExist\":"+isExist+"}");


2、站內搜索--異步顯示下拉框信息



<!-- 完成異步搜索 -->
<script type="text/javascript">

	function overFn(obj){
		$(obj).css("background","#DBEAF9");
	}
	function outFn(obj){
		$(obj).css("background","#fff");
	}
	
	function clickFn(obj){
		$("#search").val($(obj).html());
		$("#showDiv").css("display","none");
	}
	

	function searchWord(obj){
		//1、獲得輸入框的輸入的內容
		var word = $(obj).val();
		//2、根據輸入框的內容去數據庫中模糊查詢---List<Product>
		var content = "";
		$.post(
			"${pageContext.request.contextPath}/searchWord",
			{"word":word},
			function(data){
				//3、將返回的商品的名稱 現在showDiv中
				//[{"pid":"1","pname":"小米 4c 官方版","market_price":8999.0,"shop_price":8999.0,"pimage":"products/1/c_0033.jpg","pdate":"2016-08-14","is_hot":1,"pdesc":"小米 4c 標準版 全網通 白色 移動聯通電信4G手機 雙卡雙待 官方好好","pflag":0,"cid":"1"}]
				
				if(data.length>0){
					for(var i=0;i<data.length;i++){
						content+="<div style='padding:5px;cursor:pointer' onclick='clickFn(this)' onmouseover='overFn(this)' onmouseout='outFn(this)'>"+data[i]+"</div>";
					}
					$("#showDiv").html(content);
					$("#showDiv").css("display","block");
				}
				
			},
			"json"
		);
		
	}
</script>
<div class="form-group" style="position:relative">
	<input id="search" type="text" class="form-control" placeholder="Search" onkeyup="searchWord(this)">
	<div id="showDiv" style="display:none; position:absolute;z-index:1000;background:#fff; width:179px;border:1px solid #ccc;">
		
	</div>
</div>
//獲得關鍵字
String word = request.getParameter("word");
//查詢該關鍵字的所有商品
ProductService service = new ProductService();
List<Object> productList = null;
try {
	productList = service.findProductByWord(word);
} catch (SQLException e) {
	e.printStackTrace();
}
//使用json的轉換工具將對象或集合轉成json格式的字符串
Gson gson = new Gson();
String json = gson.toJson(productList);

response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json);
注意:使用json的gson轉換工具必須要導入jar包,gson-2.2.4.jar



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