js 實現對ajax請求面向對象的封裝


         AJAX 是一種用於創建高速動態網頁的技術。通過在后台與server進行少量數據交換。AJAX 能夠使網頁實現異步更新。這意味着能夠在不又一次載入整個網頁的情況下,對網頁的某部分進行更新。
        在js中使用ajax請求一般包括三個步驟:
              1、創建XMLHttp對象
              2、發送請求:包含打開鏈接、發送請求
              3、處理響應
        在不使用不論什么的js框架的情況下。要想使用ajax。可能須要向以下一樣進行代碼的編寫

var xmlHttp = xmlHttpCreate();//創建對象
xmlHttp.onreadystatechange = function(){//響應處理
	if(xmlHttp.readyState == 4){
		console.info("response finish");
		if(xmlHttp.status == 200){
			 console.info("reponse success");
			console.info(xmlHttp.responseText);
 		}
	}
}
xmlHttp.open("get","TestServlet",true);//打開鏈接

xmlHttp.send(null);//發送請求

function xmlHttpCreate() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest;// ff opera
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {

			}
		}
	}
	return xmlHttp;
}

console.info(xmlHttpCreate());

假設在比較復雜的業務邏輯里面使用這樣的ajax請求,會使得代碼非常臃腫,不方便重用,而且能夠看到,可能在server響應成功后要處理一個業務邏輯操作。這個時候不得不把操作寫在onreadystatechage方法里面。


為了方便代碼的重用我們能夠做出例如以下處理;
      1、server響應成功后,要處理的業務邏輯交給開發者自己處理
      2、對請求進行面向對象的封裝

處理之后看起來應該像以下這個樣子:
window.onload = function() {
	document.getElementById("hit").onclick = function() {
		console.info("開始請求");
		ajax.post({
				data : 'a=n',
				url : 'TestServlet',
				success : function(reponseText) {
					console.info("success : "+reponseText);
				},
				error : function(reponseText) {
					console.info("error : "+reponseText);
				}
		});
	}
}

var ajax = {
	xmlHttp : '',
	url:'',
	data:'',
	xmlHttpCreate : function() {
		var xmlHttp;
		try {
			xmlHttp = new XMLHttpRequest;// ff opera
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie
			} catch (e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {

				}
			}
		}
		return xmlHttp;
	},
	post:function(jsonObj){
		ajax.data = jsonObj.data;
		ajax.url = jsonObj.url;
		//創建XMLHttp對象,打開鏈接、請求、響應
		ajax.xmlHttp = ajax.xmlHttpCreate();
		ajax.xmlHttp.open("post",ajax.url,true);
		ajax.xmlHttp.onreadystatechange = function(){
			if(ajax.xmlHttp.readyState == 4){
				if(ajax.xmlHttp.status == 200){
					jsonObj.success(ajax.xmlHttp.responseText);
				}else{
					jsonObj.error(ajax.xmlHttp.responseText);
				}
			}
		}
		ajax.xmlHttp.send(ajax.data);
	}
};

上述代碼實現了相似jquery中的ajax操作,讀者有不懂的地方能夠慢慢思考或者在此留言 





















免責聲明!

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



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