javascript - 封装ajax
封装,使用有示例.
1 // 封装示例:
2 function ajax(url, method, params, done) {
3 var xhr = null;
4 method = method.toUpperCase();
5 xhr = window.XMLHttpRequest ? xhr = window.XMLHttpRequest : xhr = new ActiveXObject('Microsoft.XMLHTTP');
6
7 if (typeof params === 'object') {
8 var tempArr = [];
9 for (var key in params) {
10 var value = params[key];
11 tempArr.push(key + '=' + value);
12 }
13 params = tempArr.join('&');
14 }
15
16 // GET
17 if (method === 'GET') {
18 url += '?' + params;
19 }
20 xhr.open(method, url, false);
21
22 // POST
23 var data = null;
24 if (method === 'POST') {
25 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
26 data = params;
27 }
28
29 xhr.onreadystatechange = function () {
30 if (this.readyState !== 4 && this.status !== 200) return false;
31 ongone(this.responseText);
32 }
33 xhr.send(data);
34 }
35
36
37 // 调用示例:ajax('get','test.php',{id:123,},ongone)
38 ajax('GET', 'test.php', {}, ongone);
39
40 var ongone = function (res) {
41 console.log('1');
42 console.log('2');
43 console.log(res);
44 console.log('gone!');
45 }