1. 程式人生 > 其它 >原生js實現的ajax請求

原生js實現的ajax請求

技術標籤:javascriptjavascript

什麼是ajax

ajax =AsynchronousJavaScriptAndXML.

ajax 允許通過與場景後面的 Web 伺服器交換資料來非同步更新網頁。這意味著可以更新網頁的部分,而不需要重新載入整個頁面。

什麼是XMLHttpRequest

XMLHttpRequest 物件用於同後臺伺服器交換資料;所有現代瀏覽器(Chrom、IE7+、Firefox、Safari 以及 Opera)都有內建的 XMLHttpRequest 物件。

方法描述
new XMLHttpRequest()建立新的 XMLHttpRequest 物件
abort()取消請求
getAllResponseHeaders()返回頭部資訊
getResponseHeader()返回特定的頭部資訊
open(method,url,async,user,psw)

請求

  • method:請求型別 GET 或 POST
  • url:檔案路徑
  • async:true(非同步)或 false(同步)
  • 可選使用者名稱、密碼
send()將請求傳送到伺服器,用於 GET 請求
send(string)將請求傳送到伺服器,用於 POST 請求
setRequestHeader()向要傳送的報頭新增標籤/值對

XMLHttpRequest的屬性:

onreadystatechange定義當 readyState 屬性發生變化時被呼叫的函式
readyState

狀態

  • 0:請求未初始化
  • 1:伺服器連線已建立
  • 2:請求已收到
  • 3:正在處理請求
  • 4:請求已完成且響應已就緒
responseText返回字串格式響應資料
responseXML返回XML格式響應資料
status

返回狀態號

  • 200: "OK"
  • 403: "Forbidden"
  • 404: "Not Found"

ajax 如何工作:

  1. 網頁中發生一個事件(頁面載入、按鈕點選)
  2. 由 JavaScript 建立 XMLHttpRequest 物件
  3. XMLHttpRequest 物件向 web 伺服器傳送請求
  4. 伺服器處理該請求
  5. 伺服器將響應傳送回網頁
  6. 由 JavaScript 讀取響應
  7. 由 JavaScript 執行正確的動作(比如執行程式碼更新頁面)

先做一個get:


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        </head>
        <body>
        
        <p id="txt"></p>
        <button onclick="do_get()">獲取資料</button>
        </body>
<script>

function getXhr(){
	if (window.XMLHttpRequest) {
	    // 用於現代瀏覽器的程式碼
	     xmlhttp = new XMLHttpRequest();
	 } else {
	    // 應對老版本 IE 瀏覽器的程式碼
	     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	 }
	 return xmlhttp;
}

function get(url,async){
	var xhr = getXhr();
		xhr.open('GET',url,async);
		xhr.send(null);
		xhr.onreadystatechange=function(){
			if(xhr.readyState ===4){
				var text ;
				if(xhr.status === 200){
					text=xhr.responseText;
				}else{
					text='獲取失敗';
				}
				callback(text);
			}
		}
}

function callback(text){
	document.getElementById("txt").innerText=text;
}

function do_get(){
	get("ajax_test.txt",true);
}	
</script>
</html>

點選按鈕:

再看一下post:


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        </head>
        <body>
        
        <p id="txt"></p>
        <button onclick="do_post()">獲取資料</button>
        </body>
<script>

function getXhr(){
	if (window.XMLHttpRequest) {
	    // 用於現代瀏覽器的程式碼
	     xmlhttp = new XMLHttpRequest();
	 } else {
	    // 應對老版本 IE 瀏覽器的程式碼
	     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	 }
	 return xmlhttp;
}

function get(url,async){
	var xhr = getXhr();
		xhr.open('GET',url,async);
		xhr.send(null);
		xhr.onreadystatechange=function(){
			if(xhr.readyState ===4){
				var text ;
				if(xhr.status === 200){
					text=xhr.responseText;
				}else{
					text='獲取失敗';
				}
				callback(text);
			}
		}
}

function post(url,async){
	var xhr = getXhr();
		xhr.open('POST',url,async);
		//post需加上這句,不然報錯
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xhr.send();
		xhr.onreadystatechange=function(){
			if(xhr.readyState ===4){
				var text ;
				if(xhr.status === 200){
					text=xhr.responseText;
				}else{
					text='獲取失敗';
				}
				callback("POST "+text);
			}
		}
}

function callback(text){
	document.getElementById("txt").innerText=text;
}

function do_get(){
	get("ajax_test.txt",true);
}	
function do_post(){
	post("ajax_test.txt",true);
}
</script>
</html>

把get post合併起來,並加上引數的呼叫,否則太麻煩


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        </head>
        <body>
        
        <p id="txt"></p>
        <button onclick="do_ajax()">獲取資料</button>
        </body>
<script>
	function _doAjax(option){
		var xhr = window.XMLHttpRequest ? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
		if(!xhr){
			throw new Error('不支援發起http請求!');
		}
		var opt = option || {},
			url = opt.url,
			async = opt.async ,
			type = (opt.type || 'GET').toUpperCase(),
			data = opt.data || {};
			
			if(typeof async === 'undefined'){
				async = true ;//如果跨域,這個引數用false不行
			}
			if(!url){
				throw new Error('請填寫url!');
			}
			xhr.open(type,url,async);
			type === 'POST' && xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			xhr.send(type === 'GET'?null : formatData(data));
			xhr.onreadystatechange=function(){
				if(xhr.readyState ===4){
					if(xhr.status === 200){
						cb(type+" "+xhr.responseText,'suc');
					}else{
						cb(type+" "+xhr.responseText,'fail');
					}
				}
			}
				
		
		function formatData(data){
			var rData='';
			for(var key in data){
				rData += key + '=' + data[key] + '&';
			}
			return rData.replace(/&$/,'');
		}
	}
	
	function cb(text,result){
		document.getElementById("txt").innerText=text;
	}
	
	function do_ajax(){
		var option = {
			url:'ajax_test.txt',
			type:'get',
			async:true,
			data:{}
		}
		_doAjax(option);
	}
	
	
</script>
</html>

若需要修改呼叫的方式或者傳入的引數,只需要在option裡面更改即可:

歡迎指正交流,點個贊吧!!