|
| 1 | +function ajax(options) { |
| 2 | + //->init parameters |
| 3 | + var _default = { |
| 4 | + url: null, |
| 5 | + type: 'get', |
| 6 | + dataType: 'text', |
| 7 | + data: null, |
| 8 | + cache: true, |
| 9 | + async: true, |
| 10 | + success: null, |
| 11 | + error: null |
| 12 | + }; |
| 13 | + for (var key in options) { |
| 14 | + if (options.hasOwnProperty(key)) { |
| 15 | + _default[key] = options[key] |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + //->SEND AJAX |
| 20 | + var xhr = new XMLHttpRequest; |
| 21 | + //->如果当前是GET系列的请求,我们的CACHE也设置为FALSE,需要我们清除缓存:在原有的URL的末尾追加随机数即可(之前有问号我们用&符,之前没有才用?) |
| 22 | + if (/^(GET|HEAD|DELETE)$/i.test(_default.type) && _default.cache === false) { |
| 23 | + var symbol = _default.url.indexOf('?') === -1 ? '?' : '&'; |
| 24 | + _default.url += symbol + '_=' + Math.random(); |
| 25 | + } |
| 26 | + xhr.open(_default.type, _default.url, _default.async); |
| 27 | + xhr.onreadystatechange = function () { |
| 28 | + if (/^(2|3)\d{2}$/.test(xhr.status)) { |
| 29 | + if (xhr.readyState === 4) { |
| 30 | + var text = xhr.responseText; |
| 31 | + //->从服务器获取的是字符串,我们需要把它转换为我们需要的 |
| 32 | + switch (_default.dataType) { |
| 33 | + case 'json': |
| 34 | + text = 'JSON' in window ? JSON.parse(text) : eval('(' + text + ')'); |
| 35 | + break; |
| 36 | + case 'xml': |
| 37 | + text = xhr.responseXML; |
| 38 | + break; |
| 39 | + } |
| 40 | + _default.success && _default.success.call(xhr, text); |
| 41 | + } |
| 42 | + return; |
| 43 | + } |
| 44 | + if (xhr.readyState === 4) { |
| 45 | + _default.error && _default.error.call(xhr, xhr.responseText); |
| 46 | + } |
| 47 | + }; |
| 48 | + xhr.send(_default.data); |
| 49 | +} |
| 50 | + |
| 51 | +/*ajax({ |
| 52 | + url: '',//->Request URL |
| 53 | + type: '',//->HTTP METHOD 都是小写的:get(默认) post head put delete... |
| 54 | + dataType: '',//->获取的数据转换为什么样的类型(预设返回的数据类型),从服务器获取的一般都是字符串,我们可以把获取的字符串按照预定的方式进行转换 text(默认)、json、xml... |
| 55 | + data: '',//->如果是GET请求默认是null POST请求如果需要传递给服务器内容,我们把内容放到DATA中即可,一般都是JSON格式的字符串 |
| 56 | + cache: false,//->默认是TRUE 如果是GET请求,我们设置了FALSE,不想走缓存,在URL的末尾加随机数 |
| 57 | + async: true,//->默认是TRUE异步 FALSE同步 |
| 58 | + success: function (result) {//->请求成功后做的事情 |
| 59 | +
|
| 60 | + }, |
| 61 | + error: function (result) {//->请求失败后做的事情 |
| 62 | +
|
| 63 | + } |
| 64 | + });*/ |
0 commit comments