當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript——XMLHttpResquest的简单封装
生活随笔
收集整理的這篇文章主要介紹了
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.forEachformData.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
總結
以上是生活随笔為你收集整理的JavaScript——XMLHttpResquest的简单封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AJAX——AJAX请求递归
- 下一篇: Web安全——易班优课YOOC课群在线测