自己原生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