├── README.md ├── ajax(ES6).js └── ajax.js /README.md: -------------------------------------------------------------------------------- 1 | ### 轻量级ajax 2 | 3 | - 单独对ajax进行了封装,轻量,方便使用。 4 | - 如果您使用jQuery只是为了使用`$ajax()`方法的话,这个正适合您。 5 | 6 | ### 例: 7 | 8 | #### Get请求 9 | 10 | ```javascript 11 | ajax.get(url, { 12 | name: 'damonare', 13 | sex: 'man' 14 | }, function(res){ 15 | console.log(res); 16 | }, async); 17 | // 或 18 | ajax.get(url, { 19 | name: 'damonare', 20 | sex: 'man' 21 | success: function(res) {}, 22 | error: function(err) {} 23 | }); 24 | ``` 25 | 26 | #### POST请求 27 | 28 | ```javascript 29 | // json 30 | ajax.post('/', { 31 | data: { 32 | "name": "damonare", 33 | "age": 12 34 | }, 35 | dataType: 'json', 36 | contentType: 'application/json; charset=UTF-8', 37 | success: function(res) { 38 | console.log(res); 39 | }, 40 | error: function(err) { 41 | console.error(err); 42 | } 43 | }); 44 | // x-www-form-urlencoded 45 | ajax.post('/', { 46 | data: { 47 | "name": "damonare", 48 | "age": 12 49 | }, 50 | dataType: 'json', 51 | contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 52 | success: function(res) { 53 | console.log(res); 54 | }, 55 | error: function(err) { 56 | console.error(err); 57 | } 58 | }); 59 | // form-data 60 | ajax.post('/', { 61 | data: formData, 62 | dataType: 'json', 63 | success: function(res) { 64 | console.log(res); 65 | }, 66 | error: function(err) { 67 | console.error(err); 68 | } 69 | }); 70 | ``` 71 | 72 | #### XMLHttpRequest实例对象获取 73 | 74 | ```javascript 75 | // 实例对象 76 | ajax.post('/', { 77 | data: {}, 78 | xhr: function(xhr) { 79 | console.log(xhr); 80 | } 81 | }); 82 | ``` 83 | 84 | #### 同步请求(慎用) 85 | 86 | ```javascript 87 | // 实例对象 88 | ajax.get('/', { 89 | data: {} 90 | }, function() { 91 | }, false); 92 | ``` 93 | 94 | -------------------------------------------------------------------------------- /ajax(ES6).js: -------------------------------------------------------------------------------- 1 | const ajax = {}; 2 | ajax.httpRequest = () => { 3 | //判断是否支持XMLHttpRequest对象 4 | // Chrome, Firefox, Opera 8.0+, Safari 5 | if (window.XMLHttpRequest) { 6 | return new XMLHttpRequest(); 7 | } 8 | //兼容IE浏览器 9 | const versions = [ 10 | "MSXML2.XmlHttp.6.0", 11 | "MSXML2.XmlHttp.5.0", 12 | "MSXML2.XmlHttp.4.0", 13 | "MSXML2.XmlHttp.3.0", 14 | "MSXML2.XmlHttp.2.0", 15 | "Microsoft.XmlHttp" 16 | ]; 17 | //定义局部变量xhr,储存IE浏览器的ActiveXObject对象 18 | let xhr; 19 | for (let i = 0; i < versions.length; i++) { 20 | try { 21 | xhr = new ActiveXObject(versions[i]); 22 | break; 23 | } catch (e) {} 24 | } 25 | return xhr; 26 | }; 27 | 28 | ajax.send = (url, callback, method, data, async) => { 29 | //默认异步 30 | if (async === undefined) { 31 | async = true; 32 | } 33 | let httpRequest = ajax.httpRequest(); 34 | //初始化HTTP请求 35 | httpRequest.open(method, url, async); 36 | //onreadystatechange函数对象 37 | httpRequest.onreadystatechange = () => { 38 | //readyState 的值等于4,从服务器拿到了数据 39 | if (httpRequest.readyState == 4) { 40 | //回调服务器响应数据 41 | callback(httpRequest.responseText) 42 | } 43 | }; 44 | if (method == 'POST') { 45 | //给指定的HTTP请求头赋值 46 | httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 47 | } 48 | //发送HTTP请求 49 | httpRequest.send(data); 50 | }; 51 | //实现GET请求 52 | ajax.get = (url, data, callback, async) => { 53 | const query = []; 54 | for (let key in data) { 55 | query.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`); 56 | } 57 | ajax.send(`${url}${query.length ? `?${query.join('&')}` : ''}`, callback, 'GET', null, async); 58 | }; 59 | //实现POST请求 60 | ajax.post = (url, data, callback, async) => { 61 | const query = []; 62 | for (let key in data) { 63 | query.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`); 64 | } 65 | ajax.send(url, callback, 'POST', query.join('&'), async); 66 | }; 67 | -------------------------------------------------------------------------------- /ajax.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 你可知道造轮子的兴奋? 3 | */ 4 | var ajax = {}; 5 | ajax.httpRequest = function () { 6 | // 判断是否支持XMLHttpRequest对象 7 | // Chrome, Firefox, Opera 8.0+, Safari 8 | if (window.XMLHttpRequest) { 9 | return new XMLHttpRequest(); 10 | } 11 | //兼容IE浏览器 12 | var versions = [ 13 | "MSXML2.XmlHttp.6.0", 14 | "MSXML2.XmlHttp.5.0", 15 | "MSXML2.XmlHttp.4.0", 16 | "MSXML2.XmlHttp.3.0", 17 | "MSXML2.XmlHttp.2.0", 18 | "Microsoft.XmlHttp" 19 | ]; 20 | // 定义局部变量xhr,储存IE浏览器的ActiveXObject对象 21 | var xhr; 22 | for (var i = 0; i < versions.length; i++) { 23 | try { 24 | xhr = new ActiveXObject(versions[i]); 25 | break; 26 | } catch (e) { } 27 | } 28 | return xhr; 29 | }; 30 | 31 | ajax.send = function (url, callback, method, request, async) { 32 | // 默认异步 33 | if (async === undefined) { 34 | async = true; 35 | } 36 | var httpRequest = ajax.httpRequest(); 37 | var handleResult = function() { 38 | if (httpRequest.status == 200) {// 200 = OK 39 | var responseText = httpRequest.responseText; 40 | if (request.dataType && request.dataType === 'json') { 41 | responseText = JSON.parse(responseText); 42 | } 43 | callback && callback({ 44 | data: responseText, 45 | status: httpRequest.status, 46 | statusText: httpRequest.statusText, 47 | upload: httpRequest.upload 48 | }); 49 | request.success && request.success({ 50 | data: responseText, 51 | status: httpRequest.status, 52 | statusText: httpRequest.statusText, 53 | upload: httpRequest.upload 54 | }); 55 | } else { 56 | // 错误回调 57 | callback && callback({ 58 | status: httpRequest.status, 59 | statusText: httpRequest.statusText 60 | }); 61 | request.error && request.error({ 62 | status: httpRequest.status, 63 | statusText: httpRequest.statusText 64 | }); 65 | } 66 | } 67 | if (typeof callback !== 'function') { 68 | callback = function () {} 69 | } 70 | // 初始化HTTP请求 71 | httpRequest.open(method, url, async); 72 | // 获取xhr对象 73 | request.xhr && request.xhr(httpRequest); 74 | httpRequest.withCredentials = true; 75 | if (request.withCredentials !== undefined) { 76 | httpRequest.withCredentials = !!request.withCredentials; 77 | } 78 | httpRequest.ontimeout = function () { 79 | console.error("The request for " + url + " timed out."); 80 | }; 81 | httpRequest.onerror = function (e) { 82 | console.error(httpRequest.statusText); 83 | }; 84 | // onreadystatechange函数对象 85 | if (async) { 86 | httpRequest.onreadystatechange = function () { 87 | // readyState 的值等于4,从服务器拿到了数据 88 | if (httpRequest.readyState == 4) { 89 | // 回调服务器响应数据 90 | handleResult(); 91 | } 92 | }; 93 | } else { 94 | handleResult(); 95 | } 96 | 97 | if (method == 'POST' && request.contentType) { 98 | // 给指定的HTTP请求头赋值 99 | httpRequest.setRequestHeader('Content-Type', request.contentType); 100 | } 101 | // 发送HTTP请求 102 | httpRequest.send(request.data); 103 | }; 104 | // 实现GET请求 105 | ajax.get = function (url, request, callback, async) { 106 | var query = []; 107 | for (var key in request.data) { 108 | query.push(encodeURIComponent(key) + '=' + encodeURIComponent(request.data[key])); 109 | } 110 | ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', request, async) 111 | }; 112 | // 实现POST请求 113 | ajax.post = function (url, request, callback, async) { 114 | var query = []; 115 | // contentType为false的请求,不进行数据处理; 116 | if (request.contentType === false) { 117 | ajax.send(url, callback, 'POST', request, async) 118 | return; 119 | } 120 | if (request.contentType && request.contentType.match(/json/g)) { 121 | try { 122 | request.data = JSON.stringify(request.data); 123 | } catch(e) { 124 | throw new Error(err); 125 | } 126 | } else { 127 | for (var key in request.data) { 128 | query.push(encodeURIComponent(key) + '=' + encodeURIComponent(request.data[key])); 129 | } 130 | request.contentType = request.contentType || 'application/x-www-form-urlencoded; charset=UTF-8'; 131 | request.data = query.join('&'); 132 | } 133 | ajax.send(url, callback, 'POST', request, async) 134 | }; 135 | --------------------------------------------------------------------------------