手動封裝js原生XMLHttprequest非同步請求

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

CodeObject.extend =function(targetObj,fnJson){    //擴充方法,類似於jQuery的$.extend,可以擴充類的方法,也可以合并對象    for(var fnName in fnJson){        targetObj[fnName]=fnJson[fnName];    }    return targetObj;};HttpAjax = (function(){    function HttpAjax(options){        var settings={            type:‘post‘,        //請求類型            url:‘‘,             //請求地址            data:{"id":-1},     //json格式的參數            success:function(){},//成功的回呼函數            failure:function(){},//失敗的回呼函數            isAsyn:true           //是否為非同步        };        this.options = Object.extend(settings,options);        Object.extend(HttpAjax.prototype,{            _createXhr:function(){                if (typeof XMLHttpRequest !== ‘undefined‘) {                    return new XMLHttpRequest();                }                else if (typeof ActiveXObject !== ‘undefined‘) {                    var versions = [‘MSXML2.XMLHttp.6.0‘, ‘MSXML2.XMLHttp.3.0‘, ‘MSXML2.XMLHttp‘];                    for (var i = 0, len = versions.length; i < len; i++) {                        try {                            var xhr = new ActiveXObject(versions[i]);                            this.IsCreateOk = versions[i];                            return xhr;                        }                        catch (e) { }                    }                    if (typeof this.IsCreateOk === ‘undefined‘) {                        throw new Error("您的瀏覽器版本過低,無法建立非同步對象,請升級您的瀏覽器!");                    }                }            },            _encodeData:function(paramters){                var data = [];                for (var name in paramters) {                    //將數組中的資料以=拼接後再添加到data數組中 [name=aa,age=11]                    var _regesp = /%20/g; //空格的Regex                    var _value = paramters[name].toString(); //擷取值                    data.push(encodeURIComponent(name).replace(_regesp, ‘+‘) + "=" + encodeURIComponent(_value).replace(_regesp, ‘+‘));                }                //以&將數組元素拼接後返回 如:name=aa&age=11                return data.join("&");            },            _regCallback:function(xhr){                var _this=this;                xhr.onreadystatechange = function(){                    if (xhr.readyState == 4) {                        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) {                            _this.options.success(_this._getResponseData(xhr), xhr.statusText);                        } else {                            _this.options.failure(xhr.status, xhr.statusText);                        }                    }                }            },            _getResponseData:function(xhr){                var responseType = xhr.getResponseHeader("Content-Type");                switch (responseType) {                    case ‘text/xml‘:                        return xhr.responseXML;                    case ‘text/json‘:                    case ‘text/javascript‘:                    case ‘application/javascript‘:                    case ‘application/x-javascript‘:                        return eval(‘(‘ + xhr.responseText + ‘)‘);                    default:                        return xhr.responseText;                };            },            _init:function(options){                this.options=options;                if(this.options.url=="") return;                this.xhr = this._createXhr();//建立非同步對象                this._regCallback(this.xhr);//註冊回調事件                //根據請求類型,發送非同步請求                if(this.options.type.toLowerCase()=="post"){                    this._post(this.xhr);                }                else{                    this._get(this.xhr);                }            },            _post:function(xhr){                this.xhr=xhr;                this.data=this._encodeData(this.options.data);                this.url=this.options.url+"?d=" + parseInt(Math.random()*100+1,10);                this.asyn=!!this.options.isAsyn;                xhr.open("POST", this.url, this.asyn);                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                xhr.send(this.data);            },            _get:function(xhr){                this.xhr=xhr;                this.data=this._encodeData(this.options.data);                this.url=this.options.url+‘?‘ + this.data + ‘&d=‘ + parseInt(Math.random()*100+1,10);                this.asyn=!!this.options.isAsyn;                xhr.open(‘GET‘, this.url, this.asyn);                xhr.send(null);            }        });       this._init(this.options);    };    return HttpAjax;})(window);

 

Code// 調用樣本:    var ss = new HttpAjax({//get        type:"get",        url:"testAjax.php",        data:{"name":‘Jack‘},        success:function(data){            console.log(data);        },        failure:function(data){            console.log(data);        },        isAsyn:false    });    console.log(new HttpAjax({//post        type:"post",        url:"testAjax.php",        data:{"name":‘Bob‘},        success:function(data){            console.log(data);        },        failure:function(data){            console.log(data);        }    }));    new HttpAjax({//post        type:"post",        url:"testAjax.php",        data:{"name":‘Bob‘},        success:function(data){            console.log(data);        },        failure:function(data){            console.log(data);        }    });    new HttpAjax({//post        type:"post",        url:"testAjax.php",        data:{"name":‘Stack‘},        success:function(data){            console.log(data);        },        failure:function(data){            console.log(data);        }    });

Code//請求:testAjax.php?name=Jack&d=21 GET 200 testAjax.php?d=85 POST 200 testAjax.php?d=46 POST 200 //返回結果:name:Jack index.htm:134name:Stack index.htm:159name:Bob // 待完善的地方:添加預設參數:cache //是否允許緩衝添加兩個監測狀態的事件:beforeSend 、complete// php後台<?php header("Content-Type:text/html; charset=utf8");echo "name:".$_REQUEST[‘name‘]; ?>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.