1. 程式人生 > >自定義封裝ajax,復制即可用

自定義封裝ajax,復制即可用

for thead open char app gif ava message gen

支持get、post請求

  1 <!DOCTYPE html>
  2 <html>
  3 
  4     <head>
  5         <meta charset="UTF-8">
  6         <title>自定義封裝ajax</title>
  7     </head>
  8 
  9     <body>
 10     </body>
 11 
 12 </html>
 13 <script type="text/javascript"
> 14 function ajax(obj) { 15 16 obj = obj || {}; 17 obj.method = obj.method.toUpperCase() || "POST"; 18 obj.url = obj.url || ""; 19 obj.async = obj.async || true; 20 obj.data = obj.data || null; 21 obj.success = obj.success || function() {};
22 obj.headers = obj.headers || null; 23 var xmlHttp = null; 24 25 if(window.XMLHttpRequest) { 26 27 xmlHttp = new XMLHttpRequest(); //非IE瀏覽器 28 29 } else { 30 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") //IE 31 } 32 33 //
處理參數 34 35 if(obj.method.toUpperCase() == "POST") { 36 xmlHttp.open(obj.method, obj.url, obj.async); 37 38 if(obj.headers.ContentType) { 39 40 xmlHttp.setRequestHeader("Content-Type", obj.headers.ContentType); 41 42 } else { 43 44 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); 45 46 } 47 48 xmlHttp.send(JSON.stringify(obj.data)); //到了這的post是各個參數拼接在一起了,類似get請求?????????? 49 } else { 50 var par = []; 51 52 for(var key in obj.data) { 53 54 par.push(key + = + obj.data[key]) 55 56 } 57 var postData = par.join("&"); 58 59 xmlHttp.open(obj.method, obj.url + "?" + postData, obj.async); 60 xmlHttp.send(null) 61 62 } 63 64 xmlHttp.onreadystatechange = function() { 65 66 if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { 67 obj.success(JSON.parse(xmlHttp.responseText)) 68 } 69 70 } 71 72 } 73 74 //get請求實例 75 ajax({ 76 77 method: get, 78 url: "http://risk.haitun.hk/risk-console/risk/messageInfo/list", 79 data: { 80 msgType: 1, 81 pageNum: 1, 82 pageSize: 6 83 }, 84 success: function(res) { 85 console.log(res, get請求實例) 86 } 87 88 }) 89 90 //post請求實例 91 ajax({ 92 method: POST, 93 url: "http://risk.haitun.hk/risk-console/risk/riskRule/list", 94 data: { 95 pageNum: 1, 96 pageSize: 10 97 }, 98 async: false, 99 headers: { 100 "ContentType": "application/json;charset=utf-8" //註意頭部,ContentType 101 }, 102 success: function(res) { 103 104 console.log(res, post請求實例) 105 106 } 107 }) 108 </script>

自定義封裝ajax,復制即可用