一個簡單的AJAX示例


雖然現在有了框架,許多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};   
}();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM