雖然現在有了架構,許多AJAX調用直接調用它們的API就可用。但有些極端情況,比如面試,比如第三方應用不想載入這些庫,我們就只有自己寫。這時想必有許多人要瘋狂google,百度了。網上太多垃圾資訊,我還是在自己部落格上儲存一份吧。
我的實現:
var ajax = new(self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP")ajax.onreadystatechange = function(){ if (ajax.readyState==4 && ajax.status==200){ alert(ajax.responseText) }}ajax.open("POST", url, true);ajax.send("key=val&key1=val2");
群裡黑暗騎士的實現:
Ajax = function(){ function request(url,opt){ function fn(){} var async = opt.async !== false, method = opt.method || 'GET', data = opt.data || null, success = opt.success || fn, failure = opt.failure || fn; method = method.toUpperCase(); 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,success,failure); }; xhr.open(method,url,async); if(method == 'POST'){ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;'); } xhr.send(data); return xhr; } function _onStateChange(xhr,success,failure){ if(xhr.readyState == 4){ var s = xhr.status; if(s>= 200 && s < 300){ success(xhr); }else{ failure(xhr); } }else{} } return {request:request}; }();