JavaScript——XMLHttpResquest的簡單封裝

源代碼

var ajax=(options)=>{
		// 1. 首先簡單驗證傳進來的參數是否合法
		if(!options) return undefined;
		// 2. 對參數容錯處理
		options.method = options.method ? options.method.toUpperCase() : 'GET'; // 默認 GET 請求
		options.data = options.data || {};
			options.type = options.type || 'FormData';
			if(options.type==='JSON'){
					options.data = JSON.stringify(options.data)
			}else if(options.type==='FormData'){
					var formData = [];
					for(let key in options.data) {  // Object.keys.forEach
							formData.push(''.concat(key, '=', options.data[key]))
					}
					options.data = formData.join('&') //eg: a=b&c=d&e=f
			}
			// 3. 實例化 XMLHttpRequest 對象,並進行一些設置
			var xmlhttp = new XMLHttpRequest();//獲取對象
			// 4. 處理請求回調
			xmlhttp.onreadystatechange = function(){//設置回調函數
					if(xmlhttp.readyState == 4){//這裏的4是請求的狀態碼,代表請求已經完成
							if(xmlhttp.status == 200 || xmlhttp.status == 304){//這裏是獲得響應的狀態碼,200代表成功,304代表無修改可以直接從緩存中讀取
									options.success(xmlhttp)
							}else if(xmlhttp.status==500||xmlhttp.status==404){
									options.failure(xmlhttp)
							}else {
									options.failure(xmlhttp)
							}
					}
			}
			// 5. 打開請求
			xmlhttp.open(options.method,options.url,true);
			// 6. 設置請求頭
			if(options.header){
					for(let key in options.header){
							xmlhttp.setRequestHeader(key, options.header[key])
					}
			}
			// 7. 發送請求
			xmlhttp.send(options.method==='POST'?options.data:null);//GET請求
	}

DEMO

ajax({
	url: '',
	method: 'POST',
	type: 'JSON',
	data: {},
	success: function(res) {
		console.log(res)
	},
	failure: function(err) {
		console.log(err)
	} 
})

參考文章

https://www.runoob.com/ajax/ajax-examples.html

https://blog.csdn.net/tinsine/article/details/90231546

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