1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| function ajax(option) { 请求触发前操作 option.beforeSend(); 请求发送功能 var xhr = new XMLHttpRequest(); var type = option.type.toLowerCase(); var data = urlencoded(option.data); if (type === 'grt'){ xhr.open('get', option.url + '?' + data); xhr.send(); } else if (type === 'post') { xhr.open('post', option.url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(data); }
xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var res = JSON.parse(xhr.responseText); option.success(res); } option.complete();
} }; }
ajax({ type: 'post', url: 'http://www.liulongbin.top:3006/api/addbook', data: { bookname: '张三自传', author: '张三', publisher: '张三出版社' }, success: function (res) { console.log(res); }, beforeSend: function () { console.log('请求开始发送啦'); },
complete: function () { console.log('请求处理完毕啦'); } });
function urlencoded(obj) { var arr = []; for (var key in obj) { arr.push(key + '=' + obj[key]); }
return arr.join('&'); }
}
|