. 1 ( function (window) { 2 function AjaxTool () {} . 3 . 4 AjaxTool.ajaxRequest = function (param, successCallback, the failedCallback) { . 5 // 1. acquisition parameters . 6 var requestType param = [ 'requestType'] || 'GET '; // request mode . 7 var URL = param [' URL ']; // request path . 8 var paramObj param = [' paramObj ' ]; . 9 var timeOut param = [' timeOut '] || 0 ; 10 . 11 / / 2 transmission request 12 is var XHR =new XMLHttpRequest(); 13 // 判断 14 if(requestType.toLowerCase() === 'get'){ // get请求 15 var codeURL = encodeURI(url + '?' + getStrWithObject(paramObj)); 16 xhr.open('get', codeURL, true); 17 xhr.send(); 18 }else if(requestType.toLowerCase() === 'post'){ // post请求 19 var codeParam = encodeURI(getStrWithObject(paramObj)); 20 xhr.open('post', url, true); 21 // Set request header 22 is xhr.setRequestHeader ( 'the Content-the Type', 'file application / X-WWW-form-urlencoded' ); 23 is ; xhr.send (codeParam) 24 } 25 // listener response server 26 is xhr.addEventListener ( 'the readystatechange', function (EV2) { 27 IF (xhr.readyState ===. 4 ) { 28 IF (=== 200 is xhr.status ) { 29 // request succeeds 30 successCallback && successCallback (XHR); 31 is // Clear timer 32 the clearTimeout (timer); 33 is } the else { 34 is // request fails 35 the failedCallback && the failedCallback (XHR); 36 } 37 [ } 38 is }); 39 40 // 0 means unlimited time of the request 41 is var Timer = null ; 42 is IF (timeOut> 0 ) { 43 is Timer = the setTimeout ( function () { 44 is // cancellation request 45 xhr.abort (); 46 is }, timeOut); 47 } 48 }; 49 50 / * * 51 * the object into a string splice 52 is * @param {Object} paramObj 53 is * / 54 is function getStrWithObject (paramObj) { 55 var resArr = []; 56 is // 1. Conversion Object 57 is for ( var Key in paramObj) { 58 var STR Key + = '=' + paramObj [Key]; 59 resArr.push (STR); 60 } 61 is // 2. timestamp splice 62 resArr.push ( '= Random' + getRandomStr ()); 63 is 64 // 3. array translated into strings 65 return resArr.join ( '&' ); 66 } 67 68 / * * 69 * to obtain random timestamp 70 Number @Returns {} * 71 is * / 72 function getRandomStr () { 73 is return Math.random () + ( new new a Date () the getTime ().); 74 } 75 76 window.AjaxTool = AjaxTool; 77 }) (window) ;
1 <script> 2 window.addEventListener('load', function (ev) { 3 var btn = document.getElementById('send'); 4 btn.addEventListener('click', function (ev1) { 5 6 // 1. 获取用户输入的内容 7 var account = document.getElementById('account').value; 8 var pwd = document.getElementById('pwd').value; 9 var paramObj = { 10 'account': account, 11 'pwd':pwd 12 is }; 13 is 14 var param = { 15 'requestType': 'POST' , 16 'URL': 'HTTP: // localhost: 3000 / API / Five' , . 17 'timeOut': 2000 , 18 is 'paramObj' : paramObj 19 } 20 is 21 is // 2. Create a network request object 22 is AjaxTool.ajaxRequest (param, function (XHR) { 23 is the console.log ( 'success' , xhr.responseText); 24 }, function() { 25 the console.log ( 'failure' ) 26 is }) 27 }); 28 }); 29 </ Script>