js原生的Ajax


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

1)創建Ajax引擎對象

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

3)綁定提交地址

4)發送請求

5)接受響應數據

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

	function fn1(){
		//1、創建ajax引擎對象 ---- 所有的操作都是通過引擎對象
		var xmlHttp = new XMLHttpRequest();
		//2、綁定監聽 ---- 監聽服務器是否已經返回相應數據
		xmlHttp.onreadystatechange = function(){
			if(xmlHttp.readyState==4&&xmlHttp.status==200){
				//5、接受相應數據
				var res = xmlHttp.responseText;
				document.getElementById("span1").innerHTML = res;
			}
		}
		//3、綁定地址
		xmlHttp.open("GET","/WEB22/ajaxServlet?name=lisi",true);
		//4、發送請求
		xmlHttp.send();
		
	}
	function fn2(){
		//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");
		
	}

	
</script>

</head>
<body>
	<input type="button" value="異步訪問服務器端" onclick="fn1()"><span id="span1"></span>
	<br>
	<input type="button" value="同步訪問服務器端" onclick="fn2()"><span id="span2"></span>
	<br>
	<input type="button" value="測試按鈕" onclick="alert()">
</body>
</html>

  注意:

注意:如果是post提交

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

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

  get請求的請求參數在open(如fn1中的參數傳遞方法)中或send中都可以(如fn2中的參數傳遞方法)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM