原生JS封裝ajax方法


 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <meta charset="utf-8">
 5   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6   <title>Examples</title>
10   <script>
11 
12     //將對象序列化
13     function params(data) {
14       var arg = [];
15       for (var i in data) {
16         arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
17       }
18       return arr.join('&');
19     }
20 
21     //封裝ajax
22     function ajax(obj) {
23       //創建xhr對象;
24       obj.xhr = new XMLHttpRequest();
25       //后面隨機數防止瀏覽器緩存
26       obj.url = url + "?rand=" + Math.random();
27       //序列化對象
28       obj.data = params(obj.data);
29       //當是get請求時
30       if (obj.method = 'get') {
31         //當前面沒設置隨機數時
32         obj.url += obj.url.indexOf('?') == -1 ? '?' +obj.data : '&' + obj.data;
33       }
34       //異步調用
35       if (obj.async == true) {
36         //監聽響應狀態
37         xhr.onreadystatechange = function() {
38           if (xhr.readyState == 4) {
39             callback();
40           }
41         };
42       }
43       //啟動HTTP請求
44       xhr.open(obj.method, obj.url, obj.aysnc);
45       //當是post請求時
46       if(obj.method === 'post') {
47         //模仿表單提交
48         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
49         //發送HTTP請求-post
50         xhr.send(obj.data);
51       } else {
52         //發送HTTP請求-get
53         xhr.send(null);
54       }
55       //同步調用
56       if (obj.async == false) {
57         callback();
58       }
59       //回調函數傳參
60       function callback() {
61         if (xhr.atatus == 200) {
62           obj.success(xhr.responseText);
63         } else {
64           alert("失敗,失敗狀態碼:" + xhr.status);
65         }
66       }
67     }
68 
69     document.addEventListener('click', function() {
70       ajax({
71         method: 'get',
72         url: 'demo3.php',
73         data: {
74           'name' = 'Lee',
75           'age' = 100
76         },
77         success: function(text) {
78           alert(text);
79         },
80         async = true
81       });
82     }, false);
83   </script>
84 </head>
85 <body>
86     
87 </body>
88 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM