首先貼代碼 註釋: 1,open(method, url, async) method: GET和POST; url: 發送到服務端的url; async: 非同步true,同步false; 2,onreadystatechange 每當readyState的值變化,onreadystatechang ...
首先貼代碼
1 var ajaxOptions = { 2 url: 'url', 3 method: 'GET', 4 async: true, 5 data: null, 6 dataType: 'text', 7 } 8 9 function ajax(protoOptions) { 10 var options = {}; 11 12 for(var i in ajaxOptions){ 13 options[i] = protoOptions[i] || ajaxOptions[i]; 14 } 15 16 17 return new Promise(function(resolve, reject){ 18 var xhr = new XMLHttpRequest(); 19 20 xhr.open(options.method, options.url, options.async); 21 22 xhr.onreadystatechange = function() { 23 if (this.readyState === 4 && this.status === 200) { 24 resolve(this.responseText, this); 25 } else { 26 var resJson = { 27 code: this.status, 28 response: this.response 29 } 30 reject(resJson, this) 31 } 32 } 33 34 xhr.send() 35 36 }) 37 }
註釋:
1,open(method, url, async)
method: GET和POST;
url: 發送到服務端的url;
async: 非同步true,同步false;
2,onreadystatechange
每當readyState的值變化,onreadystatechange函數自動執行
3,readyState 伺服器響應的狀態信息
- 0: 請求未初始化
- 1: 伺服器連接已建立
- 2: 請求已接收
- 3: 請求處理中
- 4: 請求已完成,且響應已就緒
當readyState的值為4,status狀態為200時表示相應已就緒,可以執行成功調用的方法,反之調用失敗調用的方法