Ajax中的x指的是xml,早期的數據格式都喜歡用XML,然后一層層的解析。當然簡單的也會返回HTML(或稱HTML片段)。
現在使用JSON格式的也很多。根據不同需求,給Ajax對象添加了三個實用方法:Ajax.text、Ajax.json、Ajax.xml。
Ajax.text返回純文本,即responseText
Ajax.json返回json,即會將responseText解析成js對象
Ajax.xml返回xml文檔,即responseXML
使用方式與Ajax.request相同,第一個參數是請求url,第二個是配置參數。
完整代碼
01 | Ajax = |
02 | function(){ |
03 | function request(url,opt){ |
04 | function fn(){} |
05 | var async = opt.async !== false, |
06 | method = opt.method || 'GET', |
07 | type = opt.type || 'text', |
08 | encode = opt.encode || 'UTF-8', |
09 | data = opt.data || null, |
10 | success = opt.success || fn, |
11 | failure = opt.failure || fn; |
12 | method = method.toUpperCase(); |
13 | if(data && typeof data == 'object'){//對象轉換成字符串鍵值對 |
14 | data = _serialize(data); |
15 | } |
16 | if(method == 'GET' && data){ |
17 | url += (url.indexOf('?') == -1 ? '?' : '&') + data; |
18 | data = null; |
19 | } |
20 | var xhr = window.xmlhttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); |
21 | xhr.onreadystatechange = function(){ |
22 | _onStateChange(xhr,type,success,failure); |
23 | }; |
24 | xhr.open(method,url,async); |
25 | if(method == 'POST'){ |
26 | xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=' + encode); |
27 | } |
28 | xhr.send(data); |
29 | return xhr; |
30 | } |
31 | function _serialize(obj){ |
32 | var a = []; |
33 | for(var k in obj){ |
34 | var val = obj[k]; |
35 | if(val.constructor == Array){ |
36 | for(var i=0,len=val.length;i<len;i++){ |
37 | a.push(k + '=' + encodeURIComponent(val[i])); |
38 | } |
39 | }else{ |
40 | a.push(k + '=' + encodeURIComponent(val)); |
41 | } |
42 | } |
43 | return a.join('&'); |
44 | } |
45 | function _onStateChange(xhr,type,success,failure){ |
46 | if(xhr.readyState == 4){ |
47 | var s = xhr.status, result; |
48 | if(s>= 200 && s < 300){ |
49 | switch(type){ |
50 | case 'text': |
51 | result = xhr.responseText; |
52 | break; |
53 | case 'json': |
54 | result = function(str){ |
55 | return (new Function('return ' + str))(); |
56 | }(xhr.responseText); |
57 | break; |
58 | case 'xml': |
59 | result = xhr.responseXML; |
60 | break; |
61 | } |
62 | success(result); |
63 | }else{ |
64 | failure(xhr); |
65 | } |
66 | }else{} |
67 | } |
68 | return (function(){ |
69 | var Ajax = {request:request}, types = ['text','json','xml']; |
70 | for(var i=0,len=types.length;i<len;i++){ |
71 | Ajax[types[i]] = function(i){ |
72 | return function(url,opt){ |
73 | opt = opt || {}; |
74 | opt.type = types[i]; |
75 | return request(url,opt); |
76 | }; |
77 | }(i); |
78 | } |
79 | return Ajax; |
80 | })(); |
81 | }(); |
新聞熱點
疑難解答