結合prototype和xmlhttprequest封裝ajax請求

來源:互聯網
上載者:User

標籤:buffer   字串   XML   hang   方法   url   類型   共用   data   

由於拖延症的嚴重以及年前準備年會(借口*^__^*)導致這個小的的思考  現在才算完成再怎麼說也算是上班以來帶我的前輩第一次這麼正式的給我出題不管是出於尊重還是自我要求我都決定把它簡要的記下來...... 1.瞭解prototype       原型對象的作用,就是定義所有執行個體對象共用的屬性和方法。具體理解見實際操作中 2.給String Date等對象增加繼承方法  要求結果:比如var date = "2016-01-01 00:00:00";date.format();要求輸出"2016-01-01";eg:String.prototype.format = function(){
    return this.substring(0,10);
};
var str1 = "2016-01-01 00:00:00";
alert(str1.format(str1)); 3.瞭解xmlhttprequest,能發送及接受ajax,以及分析response對象           response屬性為唯讀,返回接收到的資料體(即body部分),他的類型可以是ArrayBuffer、Blob、Document、JSON對象、或者一個字串。由XMLHttpRequest.responseType屬性的值決定。 4.結合xmlhttprequest+prototype 自己封裝一個請求 本以為信手拈來,就這樣的隨便的敷衍寫了一下,發現各種對原生的ajax不熟悉於是仔細的看了一下原生的ajax相關的各個屬性,複習了下相關用法同時也參照了一些網路部落格綜合一下,對ajax進行了簡單的封裝XMLHttpRequest.prototype.ajax = function(type,url,data,success,error){
    var _this = this;
    if(typeof data == ‘object‘){
        var tempStr = ‘‘;
        for(var key in data){
            tempStr += key + ‘=‘ + data[key] + ‘&‘;
        }
        data = tempStr.replace(/&$/,‘‘);
    }
    if(type = ‘GET‘){
        if(data){
            this.open(‘GET‘,url + ‘?‘ + data, true);
        }else{
            this.open(‘GET‘,url + ‘?version=‘ + Math.random(),true);
        }
        this.send();
    }else if(type == ‘POST‘){
        this.open(‘POST‘,url,true);
        this.setRequestHeader("content-type","application/x-www-form-urlencoded");
        this.send(data);
    }
    this.onreadystatechange = function () {
        if(this.readyState == 4){
            if(this.status == 200){
                success(this.responseText);
            }else{
                if(error){
                    error(this.status);
                }
            }
        }
    }
};

//ajax test
var xhr = new XMLHttpRequest();
xhr.ajax(‘GET‘,‘https://secure.ec.qa.sunyuki.com/v0/items/11111‘,null,function(data){
    alert(data);
});  

結合prototype和xmlhttprequest封裝ajax請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.