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,第二个是配置参数。
/** * 1,执行基本ajax请求,返回XMLHttpRequest * Ajax.request(url,{ * async 是否异步 true(默认) * method 请求方式 POST or GET(默认) * type 数据格式 text(默认) or xml or json * encode 请求的编码 UTF-8(默认) * data 请求参数 (字符串或json) * success 请求成功后响应函数 参数为text,json,xml数据 * failure 请求失败后响应函数 参数为xmlHttp * }); * * 2,执行ajax请求,返回纯文本 * Ajax.text(url,{ * ... * }); * * 3,执行ajax请求,返回JSON * Ajax.json(url,{ * ... * }); * * 4,执行ajax请求,返回XML * Ajax.xml(url,{ * ... * }); */ var Ajax = function(){ function request(url,opt){ function fn(){} var async = opt.async !== false, method = opt.method || 'GET', type = opt.type || 'text', encode = opt.encode || 'UTF-8', data = opt.data || null, success = opt.success || fn, failure = opt.failure || fn; method = method.toUpperCase(); if(data && typeof data == 'object'){//对象转换成字符串键值对 data = _serialize(data); } if(method == 'GET' && data){ url += (url.indexOf('?') == -1 ? '?' : '&') + data; data = null; } var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.onreadystatechange = function(){ _onStateChange(xhr,type,success,failure); }; xhr.open(method,url,async); if(method == 'POST'){ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=' + encode); } xhr.send(data); return xhr; } function _serialize(obj){ var a = []; for(var k in obj){ var val = obj[k]; if(val.constructor == Array){ for(var i=0,len=val.length;i<len;i++){ a.push(k + '=' + encodeURIComponent(val[i])); } }else{ a.push(k + '=' + encodeURIComponent(val)); } } return a.join('&'); } function _onStateChange(xhr,type,success,failure){ if(xhr.readyState == 4){ var s = xhr.status, result; if(s>= 200 && s < 300){ switch(type){ case 'text': result = xhr.responseText; break; case 'json': result = function(str){ return (new Function('return ' + str))(); }(xhr.responseText); break; case 'xml': result = xhr.responseXML; break; } success(result); }else{ failure(xhr); } }else{} } return (function(){ var Ajax = {request:request}, types = ['text','json','xml']; for(var i=0,len=types.length;i<len;i++){ Ajax[types[i]] = function(i){ return function(url,opt){ opt = opt || {}; opt.type = types[i]; return request(url,opt); }; }(i); } return Ajax; })(); }();