封裝一個Ajax工具函數

來源:互聯網
上載者:User

標籤:

/*封裝一個ajax工具函數*/

window.$ = {};

/*通過$定義一個ajax函數*/

 

/*

* 1. type   string   請求的方式  預設是get

* 2. url    string   請求地址  介面地址

* 3. async  boolean  預設的是true

* 4. data   object   {}請求資料

*

* 5.success function  成功回呼函數

* 6.error   function  失敗的回呼函數

* */

$.ajax = function(options){

 

    if(!options) return false;

 

    /*options 參數傳遞*/

    var type = options.type || ‘get‘;

    var url = options.url || location.pathname;

    var async = options.async === false ? false : true;

    var data = options.data || {};

 

    /*data 選要轉化成  name=xjj&age=10*/

    var dataStr = ‘‘;

    for(var key in data){

        //console.log(data[key]);

        dataStr += key+‘=‘+data[key]+‘&‘;

    }

 

    /*如果就資料  就裁剪掉最後一個&*/

    dataStr = dataStr && dataStr.slice(0,-1);

 

 

    /*ajax 編程*/

    /*初始化*/

    var xhr = new XMLHttpRequest();

 

    /*請求行*/

    /*如果是get請求那麼就要拼接資料在url後面 ?*/

    xhr.open(type,type == ‘get‘?url+‘?‘+dataStr:url,async);

 

    /*要求標頭*/

    /*如果是post請求需要設定 content-type application/x-www-form-urlencoded*/

    if(type == ‘post‘){

        xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);

    }

 

    options.beforeSend && options.beforeSend();

 

    /*請求主體*/

    /*如果是post請求需要把資料字元傳過去  否則是null*/

    xhr.send(type==‘get‘?null:dataStr);

 

    /*監聽響應狀態的改變*/

    xhr.onreadystatechange = function(){

        /*響應成功*/

        if(xhr.readyState == 4){

            if( xhr.status == 200){

                /*處理響應成功函數*/

                var result = ‘‘;

                /*接受資料*/

                /* json  xml  string*/

                var contentType = xhr.getResponseHeader(‘Content-Type‘);

 

                if(contentType.indexOf(‘xml‘) > -1){

                    /*服務端返回的是xml資料格式*/

                    result = xhr.responseXML;

                }else if(contentType.indexOf(‘json‘) > -1){

                    /*服務端返回的是json資料格式*/

                    /*json字串*/

                    var str  = xhr.responseText;

                    result = JSON.parse(str);

                }else{

                    result = xhr.responseText;

                }

 

                /*調用回呼函數*/

                options.success && options.success(result);

            }

            /*響應失敗*/

            else{

                /*處理響應失敗函數*/

                options.error && options.error(‘request fail code‘ + xhr.status);

            }

 

            options.complete &&  options.complete();

        }

    }

};

 

$.get = function(options){

    options.type = ‘get‘;

    $.ajax(options);

};

$.post = function(options){

    options.type = ‘post‘;

    $.ajax(options);

};

 

/*封裝一個ajax工具函數*/window.$ = {};/*通過$定義一個ajax函數*/
/** 1. type   string   請求的方式  預設是get* 2. url    string   請求地址  介面地址* 3. async  boolean  預設的是true* 4. data   object   {}請求資料** 5.success function  成功回呼函數* 6.error   function  失敗的回呼函數* */$.ajax = function(options){
    if(!options) return false;
    /*options 參數傳遞*/    var type = options.type || ‘get‘;    var url = options.url || location.pathname;    var async = options.async === false ? false : true;    var data = options.data || {};
    /*data 選要轉化成  name=xjj&age=10*/    var dataStr = ‘‘;    for(var key in data){        //console.log(data[key]);        dataStr += key+‘=‘+data[key]+‘&‘;    }
    /*如果就資料  就裁剪掉最後一個&*/    dataStr = dataStr && dataStr.slice(0,-1);

    /*ajax 編程*/    /*初始化*/    var xhr = new XMLHttpRequest();
    /*請求行*/    /*如果是get請求那麼就要拼接資料在url後面 ?*/    xhr.open(type,type == ‘get‘?url+‘?‘+dataStr:url,async);
    /*要求標頭*/    /*如果是post請求需要設定 content-type application/x-www-form-urlencoded*/    if(type == ‘post‘){        xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);    }
    options.beforeSend && options.beforeSend();
    /*請求主體*/    /*如果是post請求需要把資料字元傳過去  否則是null*/    xhr.send(type==‘get‘?null:dataStr);
    /*監聽響應狀態的改變*/    xhr.onreadystatechange = function(){        /*響應成功*/        if(xhr.readyState == 4){            if( xhr.status == 200){                /*處理響應成功函數*/                var result = ‘‘;                /*接受資料*/                /* json  xml  string*/                var contentType = xhr.getResponseHeader(‘Content-Type‘);
                if(contentType.indexOf(‘xml‘) > -1){                    /*服務端返回的是xml資料格式*/                    result = xhr.responseXML;                }else if(contentType.indexOf(‘json‘) > -1){                    /*服務端返回的是json資料格式*/                    /*json字串*/                    var str  = xhr.responseText;                    result = JSON.parse(str);                }else{                    result = xhr.responseText;                }
                /*調用回呼函數*/                options.success && options.success(result);            }            /*響應失敗*/            else{                /*處理響應失敗函數*/                options.error && options.error(‘request fail code‘ + xhr.status);            }
            options.complete &&  options.complete();        }    }};
$.get = function(options){    options.type = ‘get‘;    $.ajax(options);};$.post = function(options){    options.type = ‘post‘;    $.ajax(options);};

 

封裝一個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.