首页 > 代码库 > 原生JS写的ajax函数
原生JS写的ajax函数
参照JQuery中的ajax功能,用原生JS写了一个ajax,功能相对JQuery要少很多,不过基本功能都有,包括JSONP。
调用的方式分为两种:
1. ajax(url, {});
2. ajax({});
调用的方法参照JQuery的ajax,只是 不需要写$.ajax ,只需要写 ajax 就可以了。
代码如下:
!function () { var jsonp_idx = 1; return 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 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; } function ajaxJSONP(url, jsonp, jsonpCallback, callback) { if (!jsonpCallback) { 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 = http://www.mamicode.com/src;"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, ‘‘)); } } } } } }();
压缩后的代码:
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;6 1V=3(a,b){5(j a==="K"){b=a;a=1o}7 o={q:b.q===p?p:Q,v:a||b.v||\‘\‘,E:b.E||k,u:(b.u||\‘W\‘).Z(),w:(b.w||\‘y\‘).Z(),R:b.R||"1y/x-1C-1F-1G; 1H=1O-8",J:b.J||"l",N:b.N||\‘\‘,l:b.l||b.2a||k,I:b.I||k,G:b.G||1B,h:\‘\‘};5(o.w===\‘1D\‘&&o.J!==p){6 1i(o.v,o.J,o.N,o.l)||p}5(o.q===Q&&j o.l!==\‘3\‘){6 p}5(o.w===\‘1j\‘||1k(o.v)){o.u=\‘1J\‘;o.v+=(/\\?/.U(o.v)?"&":"?")+9 X().Y()}7 c=9 10();5(o.q===Q){c.G=o.G}c.2b(o.u,o.v,o.q);c.2c=3(){5(4===c.1q){o.h=c.1s;5(1t===c.1u){1x(o.w){11\‘y\‘:o.h=15(o.h);16;11\‘1c\‘:o.h=1p(c.1E);16}5(j o.l===\‘3\‘){o.l(o.h,c.1f,c);5(o.w===\‘1j\‘){D(o.h)}}}A{j o.I===\‘3\‘?3(){o.I(o.h,c.1f,c)}():C(o.h);}c=k}};5(\‘W\‘===o.u){c.2g("1Q-u",o.R)}c.1T(o.E);5(o.q===p){6 o.h}};3 10(){6 3(){7 a=1n.P;V(7 i=0;i<a;i++){S{6 1n[i]()}T(e){}}}(3(){6 9 2f()},3(){6 9 L(\‘1r.12\‘)},3(){6 9 L(\‘13.12\‘)})}3 C(a){S{14.1v();14.1w(\‘E:\\r\\n\\t\‘,a)}T(e){}1z 9 1A(a);}3 15(a){5(j a!=="17"||!a){6 k}5(j 18==\‘K\‘){6 18.19(a)}A 5(j y==\‘K\‘){6 y.19(a)}A{6(9 1a("6 "+a))()}C("1b y: "+a);}3 1p(a){5(j a!=="17"||!a){6 k}7 b,M;S{5(F.1d){M=9 1d();b=M.1I(a,"1e/1K")}A{b=9 L("13.1L");b.q="p";b.1M(a)}}T(e){b=1o}5(!b||!b.1N||b.O("1P").P){C("1b 1c: "+a);}6 b}3 1i(b,c,d,e){5(!d){d=\‘1R\‘+9 X().Y()+\‘1S\‘+f++;F[d]=3(a){1g(d);e(a)}}b+=(/\\?/.U(b)?"&":"?")+c+"="+d;6 1h(d,b)}3 1h(a,b){7 c=H.1U("B");c.1W=a;c.u="1e/1X";c.1Y=b;H.O("z")[0].1Z(c);6 c}3 1g(a){7 b=H.20(a),z=H.O("z")[0];5(z&&b!=k&&b.21){z.22(b)}}3 1k(a){a=(a||\‘\‘).23(\‘?\‘)[0];7 b=a.24(a.25(\‘.\‘));6/(26|27|28|29)/1l.U(b)}3 D(b){7 c=b.1m(/<B(.|\\n)*?>(.|\\n|\\r\\n)*?<\\/B>/1l);5(c){7 d=c.P;V(7 i=0;i<d;i++){7 m=c[i].1m(/<B(.|\\n)*?>((.|\\n|\\r\\n)*)?<\\/B>/2d);5(m[2]){5(F.D){F.D(m[2])}A{(3(a){6(9 1a("6 "+a))()})(m[2].2e(/(^[\\s]*)|([\\s]*$)/g,\‘\‘))}}}}}}();‘,62,141,‘|||function||if|return|var||new||||||||result||typeof|null|callback||||false|async||||type|url|dataType||JSON|head|else|script|throwError|execScript|data|window|timeout|document|error|jsonp|object|ActiveXObject|tmp|jsonpCallback|getElementsByTagName|length|true|contentType|try|catch|test|for|POST|Date|getTime|toUpperCase|XmlHttpRequest|case|XMLHTTP|Microsoft|console|parseJSON|break|string|JSON2|parse|Function|Invalid|XML|DOMParser|text|statusText|removeScript|createScript|ajaxJSONP|HTML|checkStaticFile|ig|match|arguments|undefined|parseXML|readyState|Msxml2|responseText|200|status|trace|log|switch|application|throw|Error|4000|www|JSONP|responseXML|form|urlencoded|charset|parseFromString|GET|xml|XMLDOM|loadXML|documentElement|utf|parsererror|content|jsonpCallback_|_|send|createElement|ajax|id|javascript|src|appendChild|getElementById|parentNode|removeChild|split|substr|lastIndexOf|html|htm|txt|json|success|open|onreadystatechange|im|replace|XMLHttpRequest|setRequestHeader‘.split(‘|‘),0,{}))
原生JS写的ajax函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。