以最原始的XMLHttpRequest形式,實現ajax.ajax
封裝的方法json
1 /** 2 * 發送一個 AJAX 請求 3 * @param {String} method 請求方法 4 * @param {String} url 請求地址 5 * @param {Object} params 請求參數 6 * @param {Function} done 請求完成事後須要作的事情(委託/回調) 7 */ 8 function commonAjax (method, url, params, done) { 9 // 統一轉換爲大寫便於後續判斷 10 method = method.toUpperCase() 11 // 對象形式的參數轉換爲 urlencoded 格式 12 var pairs = [] 13 for (var key in params) { 14 pairs.push(key + '=' + params[key]) 15 } 16 var querystring = pairs.join('&') 17 var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new 18 ActiveXObject('Microsoft.XMLHTTP') 19 xhr.addEventListener('readystatechange', function () { 20 if (this.readyState !== 4) return 21 // 嘗試經過 JSON 格式解析響應體 22 try { 23 done(JSON.parse(this.responseText)) 24 } catch (e) { 25 done(this.responseText) 26 } 27 }) 28 // 若是是 GET 請求就設置 URL 地址 問號參數 29 if (method === 'GET') { 30 url += '?' + querystring 31 } 32 xhr.open(method, url) 33 // 若是是 POST 請求就設置請求體 34 var data = null 35 if (method === 'POST') { 36 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') 37 data = querystring 38 } 39 xhr.send(data) 40 }
調用:oracle
1 //1. 獲取界面上的元素 value 2 var txtUsername = "admin"; 3 var txtPassword = "admin"; 4 5 var url = 'http://127.0.0.1:8080/platform_oracle/app/userController/selectUserByUserCode.do'; 6 var params= { userCode: txtUsername, userPwd: txtPassword }; 7 8 commonAjax('post',url,params,function (data){ 9 console.log(data); 10 });
返回值:app
json格式化後的結果post
1 { 2 "MSG_ID": "SUCCESS", 3 "RESULT_CODE": "1", 4 "MSG_CONTENT": "獲取成功!", 5 "Content": { 6 "id": "E9EE2E1D4B834C59AA9719A7ADB0BA41", 7 "password": "21232F297A57A5A743894A0E4A801FC3", 8 "status": "1", 9 "userName": "admin", 10 "orgCode": null, 11 "orgName": "xxx軟件", 12 "userCode": "admin", 13 "updateUser": null, 14 "jobNum": "000000", 15 "createUser": null, 16 "cellPhone": "11111", 17 "createTime": null, 18 "updateTime": null, 19 "roleName": null, 20 "delFlag": "0", 21 "icon": null 22 } 23 }