原生JS写的ajax函数

参照JQuery中的ajax功能,用原生JS写了一个ajax,功能相对JQuery要少很多,不过基本功能都有,包括JSONP。

调用的方式分为两种:

1. ajax(url, {});

2. ajax({});

调用的方法参照JQuery的ajax,只是 不需要写$.ajax ,只需要写 ajax 就可以了。

代码如下:

!function () {
var jsonp_idx = 1; var ajax = function (url, options) {
if (typeof url === "object") {
options = url;
url = undefined;
}
var o = {
async: options.async === false ? false : true,
url: url || options.url || '',
data: options.data || null,
type: (options.type || 'POST').toUpperCase(),
dataType: (options.dataType || 'JSON').toUpperCase(), //text,json,jsonp,html,xml
contentType: options.contentType || "application/x-www-form-urlencoded; charset=utf-8",
jsonp: options.jsonp || "callback",
jsonpCallback: options.jsonpCallback || '',
callback: options.callback || options.success || null,
error: options.error || null,
timeout: options.timeout || 4000,
result: ''
}; if (o.dataType === 'JSONP' && o.jsonp !== false) {
return ajaxJSONP(o.url, o.jsonp, o.jsonpCallback, o.callback) || false;
} if (o.async === true && typeof o.callback !== 'function') {
return false;
} if (o.dataType === 'HTML' || checkStaticFile(o.url)) {
//由于大多数WEB服务器不允许静态文件响应POST请求(会返回 405 Method Not Allowed),所以改为GET请求
o.type = 'GET';
o.url += (/\?/.test(o.url) ? "&" : "?") + new Date().getTime();
} var xhr = new XmlHttpRequest(); if (o.async === true) {
xhr.timeout = o.timeout;
} xhr.open(o.type, o.url, o.async); xhr.onreadystatechange = function () {
if (4 === xhr.readyState) {
o.result = xhr.responseText;
if (200 === xhr.status) {
switch (o.dataType) {
case 'JSON':
o.result = parseJSON(o.result);
break;
case 'XML':
o.result = parseXML(xhr.responseXML);
break;
}
if (typeof o.callback === 'function') {
o.callback(o.result, xhr.statusText, xhr); if (o.dataType === 'HTML') {
//执行HTML文件中的JS代码
execScript(o.result);
}
}
} else {
typeof o.error === 'function' ? function () { o.error(o.result, xhr.statusText, xhr); }() : throwError(o.result);
}
xhr = null;
}
}; if ('POST' === o.type) {
xhr.setRequestHeader("content-type", o.contentType);
} xhr.send(o.data); if (o.async === false) {
return o.result;
}
}; function XmlHttpRequest() {
return function () {
var len = arguments.length;
for (var i = 0; i < len; i++) {
try { return arguments[i](); } catch (e) { }
}
}(function () { return new XMLHttpRequest() },
function () { return new ActiveXObject('Msxml2.XMLHTTP') },
function () { return new ActiveXObject('Microsoft.XMLHTTP') });
} function ajaxJSONP(url, jsonp, jsonpCallback, callback) {
//if (!jsonpCallback) {
//不管有没有指定JSONP回调函数,都自动生成回调函数,然后取出数据给ajax回调函数
if (!jsonpCallback || true) {
jsonpCallback = 'jsonpCallback_' + new Date().getTime() + '_' + jsonp_idx++; window[jsonpCallback] = function (result) {
removeScript(jsonpCallback);
callback(result);
};
} url += (/\?/.test(url) ? "&" : "?") + jsonp + "=" + jsonpCallback; return createScript(jsonpCallback, url);
} function createScript(id, src) {
var obj = document.createElement("script");
obj.id = id;
obj.type = "text/javascript";
obj.src = src;
document.getElementsByTagName("head")[0].appendChild(obj); return obj;
} function removeScript(id) {
var script = document.getElementById(id), head = document.getElementsByTagName("head")[0];
if (head && script != null && script.parentNode) {
head.removeChild(script);
}
} function checkStaticFile(url) {
url = (url || '').split('?')[0];
var ext = url.substr(url.lastIndexOf('.')); return /(html|htm|txt|json)/ig.test(ext);
} function execScript(html) {
var ms = html.match(/<script(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig);
if (ms) {
var len = ms.length;
for (var i = 0; i < len; i++) {
var m = ms[i].match(/<script(.|\n)*?>((.|\n|\r\n)*)?<\/script>/im);
if (m[2]) {
if (window.execScript) {
window.execScript(m[2]);
} else {
//window.eval(m[2]);
(function (data) {
return (new Function("return " + data))();
})(m[2].replace(/(^[\s]*)|([\s]*$)/g, ''));
}
}
}
}
} function throwError(err) {
try {
console.trace();
console.log('data:\r\n\t', err);
} catch (e) { }
throw new Error(err);
} function parseJSON(data) {
if (typeof data !== "string" || !data) {
return null;
}
if (typeof JSON2 === 'object') {
return JSON2.parse(data);
} else if (typeof JSON === 'object') {
return JSON.parse(data);
} else {
return (new Function("return " + data))();
} throwError("Invalid JSON: " + data);
} function parseXML(data) {
if (typeof data !== "string" || !data) {
return null;
}
var xml, tmp;
try {
if (window.DOMParser) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(data);
}
} catch (e) {
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
throwError("Invalid XML: " + data);
}
return xml;
} window.ajax = ajax;
}();

    

压缩后的代码:

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('!3(){7 f=1;7 g=3(a,b){5(j a==="R"){b=a;a=1b}7 o={u:b.u===q?q:I,p:a||b.p||\'\',F:b.F||l,k:(b.k||\'1o\').W(),w:(b.w||\'y\').W(),N:b.N||"1X/x-20-1x-1z; 1B=1G-8",J:b.J||"v",L:b.L||\'\',v:b.v||b.1Y||l,D:b.D||l,K:b.K||1w,h:\'\'};5(o.w===\'1y\'&&o.J!==q){6 1e(o.p,o.J,o.L,o.v)||q}5(o.u===I&&j o.v!==\'3\'){6 q}5(o.w===\'1f\'||1g(o.p)){o.k=\'1S\';o.p+=(/\\?/.U(o.p)?"&":"?")+9 X().Y()}7 c=9 10();5(o.u===I){c.K=o.K}c.25(o.k,o.p,o.u);c.26=3(){5(4===c.27){o.h=c.29;5(1r===c.1s){1t(o.w){11\'y\':o.h=14(o.h);15;11\'1p\':o.h=18(c.1D);15}5(j o.v===\'3\'){o.v(o.h,c.1a,c);5(o.w===\'1f\'){E(o.h)}}}z{j o.D===\'3\'?3(){o.D(o.h,c.1a,c)}():H(o.h);}c=l}};5(\'1o\'===o.k){c.2g("1U-k",o.N)}c.1V(o.F);5(o.u===q){6 o.h}};3 10(){6 3(){7 a=1h.O;V(7 i=0;i<a;i++){S{6 1h[i]()}T(e){}}}(3(){6 9 28()},3(){6 9 M(\'1q.12\')},3(){6 9 M(\'13.12\')})}3 1e(b,c,d,e){5(!d||I){d=\'1u\'+9 X().Y()+\'1v\'+f++;A[d]=3(a){16(d);e(a)}}b+=(/\\?/.U(b)?"&":"?")+c+"="+d;6 17(d,b)}3 17(a,b){7 c=G.1A("B");c.1C=a;c.k="19/1E";c.1F=b;G.Q("C")[0].1H(c);6 c}3 16(a){7 b=G.1I(a),C=G.Q("C")[0];5(C&&b!=l&&b.1J){C.1K(b)}}3 1g(a){a=(a||\'\').1L(\'?\')[0];7 b=a.1M(a.1N(\'.\'));6/(1O|1P|1Q|1R)/1c.U(b)}3 E(b){7 c=b.1d(/<B(.|\\n)*?>(.|\\n|\\r\\n)*?<\\/B>/1c);5(c){7 d=c.O;V(7 i=0;i<d;i++){7 m=c[i].1d(/<B(.|\\n)*?>((.|\\n|\\r\\n)*)?<\\/B>/1W);5(m[2]){5(A.E){A.E(m[2])}z{(3(a){6(9 1i("6 "+a))()})(m[2].1Z(/(^[\\s]*)|([\\s]*$)/g,\'\'))}}}}}3 H(a){S{1j.21();1j.22(\'F:\\r\\n\\t\',a)}T(e){}23 9 24(a);}3 14(a){5(j a!=="1k"||!a){6 l}5(j 1l===\'R\'){6 1l.1m(a)}z 5(j y===\'R\'){6 y.1m(a)}z{6(9 1i("6 "+a))()}H("1n y: "+a);}3 18(a){5(j a!=="1k"||!a){6 l}7 b,P;S{5(A.Z){P=9 Z();b=P.2a(a,"19/2b")}z{b=9 M("13.2c");b.u="q";b.2d(a)}}T(e){b=1b}5(!b||!b.2e||b.Q("2f").O){H("1n 1p: "+a);}6 b}A.1T=g}();',62,141,'|||function||if|return|var||new||||||||result||typeof|type|null||||url|false||||async|callback|dataType||JSON|else|window|script|head|error|execScript|data|document|throwError|true|jsonp|timeout|jsonpCallback|ActiveXObject|contentType|length|tmp|getElementsByTagName|object|try|catch|test|for|toUpperCase|Date|getTime|DOMParser|XmlHttpRequest|case|XMLHTTP|Microsoft|parseJSON|break|removeScript|createScript|parseXML|text|statusText|undefined|ig|match|ajaxJSONP|HTML|checkStaticFile|arguments|Function|console|string|JSON2|parse|Invalid|POST|XML|Msxml2|200|status|switch|jsonpCallback_|_|4000|form|JSONP|urlencoded|createElement|charset|id|responseXML|javascript|src|utf|appendChild|getElementById|parentNode|removeChild|split|substr|lastIndexOf|html|htm|txt|json|GET|ajax|content|send|im|application|success|replace|www|trace|log|throw|Error|open|onreadystatechange|readyState|XMLHttpRequest|responseText|parseFromString|xml|XMLDOM|loadXML|documentElement|parsererror|setRequestHeader'.split('|'),0,{}))

  

 

上一篇:原生和jquery 的 ajax


下一篇:框架----Django之Ajax全套实例(原生AJAX,jQuery Ajax,“伪”AJAX,JSONP,CORS)