自己原生js封裝的ajax請求
- 2019 年 11 月 13 日
- 筆記
前言
這幾天在惡(xue)補(xi)node.js,其中老師講到了ajax,以前學習js都是東一點、西一點。不系統,當然,原因也很多。
當時一些js基礎知識也欠缺(雖然現在也不咋的),想要自己封裝,難度也很大。
今天也終於自己封裝一個簡易 的ajax。
細節
發送POST數據,需要設置header頭:
將 Content-Type 頭部資訊設置為 application/x-www-form-urlencoded
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");完整程式碼參考:
(function (w) { var responseType = function (type, content) { switch (type) { case 'TEXT': return content; case 'JSON': return JSON.parse(content); default: return content; } }; var param = function (a) { var s = [], rbracket = /[]$/, isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }, add = function (k, v) { v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v; s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v); }, buildParams = function (prefix, obj) { var i, len, key; if (prefix) { if (isArray(obj)) { for (i = 0, len = obj.length; i < len; i++) { if (rbracket.test(prefix)) { add(prefix, obj[i]); } else { buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]); } } } else if (obj && String(obj) === '[object Object]') { for (key in obj) { buildParams(prefix + '[' + key + ']', obj[key]); } } else { add(prefix, obj); } } else if (isArray(obj)) { for (i = 0, len = obj.length; i < len; i++) { add(obj[i].name, obj[i].value); } } else { for (key in obj) { buildParams(key, obj[key]); } } return s; }; return buildParams('', a).join('&').replace(/%20/g, '+'); }; async function ajax(options) { options.method = options.method ? options.method.toUpperCase() : 'GET'; options.dataType = options.dataType ? options.dataType.toUpperCase() : 'TEXT'; options.data = options.data ? options.data : ''; options.success = options.success ? options.success : function () { }; options.fail = options.fail ? options.fail : function () { }; if (!options.url) { throw new Error("there are no url."); } var ajax = new XMLHttpRequest(); ajax.open(options.method, options.url, true); if (options.method === 'POST') { ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send(typeof options.data === 'object' ? param(options.data) : options.data); } else { ajax.send(); } ajax.onreadystatechange = function () { if (ajax.readyState === 4) { if (ajax.status === 200 || ajax.status === 301) { options.success(responseType(options.dataType, ajax.responseText)); } else { throw new Error("the status of this request is't done."); } } }; } w.ajax = ajax; })(window);其中param函數是參考:https://www.cnblogs.com/daysme/p/6651382.html
目的是發送post時,如果data參數是對象,那麼將其轉換為字元串類型。
使用
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Title</title> <script src="ajax.js"></script> <script> window.onload = function () { let oBtn = document.getElementById('btn'); oBtn.onclick = function () { ajax({ url: 'http://localhost:3000', method: 'post', data: 'aa=ff&dd=afjalk', success: function (res) { console.log(res); }, dataType: 'json' }) }; }; </script> </head> <body> <button id="btn">Request</button> </body> </html>核心就是:
ajax({ url: 'http://localhost:3000', method: 'post', data: 'aa=ff&dd=afjalk', // data可以是這種字元串,也可以是對象{} success: function (res) { console.log(res); }, dataType: 'json' })壓縮文件下載:ajax.min.js
