Ajax之三:结果分类
中的x指的是XML,早期的数据格式都喜欢用XML,然后一层层的解析。当然简单的也会返回HTML(或称HTML片段)。
现在使用ON格式的也很多。根据不同需求,给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 }();