簡單封裝原生AJAX
阿新 • • 發佈:2021-01-21
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX</title> </head> <body> <!-- 非同步的javascript和XML --> <script> ;((function() { const root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || Function('return this')() || {}; root.$$ = ((function(root) { let format = function (obj) { let r = ''; for (let key in obj) { r = r + key + '=' + obj[key] + '&'; } return r.substr(0, r.length - 1); }; let request= function (obj) { let xhr = null; if (root.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (root.ActiveXObject) { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } else { throw new Error('請在支援ajax的環境下執行此指令碼'); } if (obj.url == void 0) { throw new Error('請指定要請求的地址'); } xhr.onreadystatechange = function () { if (xhr.readyState == 4) { let res = JSON.parse(xhr.responseText); if (xhr.status == 200) { obj.success(res); } if (xhr.status == 404) { obj.fail(res); } obj.complete(res); } }; xhr.open(obj.type, obj.url, true); obj.type == 'POST' && xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(obj.type == 'GET' ? null : format(obj.data)); }; return { get: function (url, success = res => void 0, fail = res => void 0, complete = res => void 0) { request({ type: 'GET', url, success, fail, complete }); }, post: function (url, data = {}, success = res => void 0, fail = res => void 0, complete = res => void 0) { request({ type: 'POST', url, data, success, fail, complete }); } }; })(root)); })()); /** * GET: $$.get(請求地址,成功回撥,失敗回撥,完成回撥); * POST: $$.post(請求地址,請求資料,成功回撥,失敗回撥,完成回撥); */ </script> </body> </html>