原生js封裝ajax方法,包含jsonp和網絡超時處理


function ajax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || 'json';
    options.async = options.async || true;
    options.timeout=options.timeout||8000;//超時處理,默認8s
    var params = getParams(options.data);
    var timeoutFlag=null;
    var xhr;
    var that=this;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xhr.onreadystatechange = function() {
        if(options.dataType === 'json'){
            if (xhr.readyState == 4) {
                window.clearTimeout(that.timeoutFlag);
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    // 如果需要像 html 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 http 頭。
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        } else {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                window.clearTimeout(that.timeoutFlag);
                var oScript = document.createElement('script');
                document.body.appendChild(oScript);
                var callbackname = 'ajaxCallBack'
                oScript.src = options.url + "?" +  params+'&callback='+callbackname;

                window['ajaxCallBack'] = function(data) {
                    options.success(data);
                    document.body.removeChild(oScript);
                };
            }
        }
    };
    if (options.type == 'GET') {
        xhr.open("GET", options.url + '?' + params, options.async);
        xhr.send(null)
    } else if (options.type == 'POST') {
        xhr.open('POST', options.url, options.async);
        if(options.contentType=="undefined"||options.contentType==null){
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        }else{
            xhr.setRequestHeader('Content-Type', options.contentType);
            xhr.send(JSON.stringify(options.data));
        }
    }
    this.timeoutFlag=window.setTimeout(function(){//計時器,超時后處理
        window.clearTimeout(that.timeoutFlag);
        //options.fail("timeout");
        xhr.abort();
    }.bind(this),options.timeout);
}
function getParams(data) {
    var arr = [];
    for (var param in data) {
        arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
    }
    return arr.join('&');
}

調用方法:

ajax({
    url: "", //請求地址
    type: 'GET', //請求方式
    async:true,//同步異步設置
    timeout:8000,//超時設置
    data: {
        name: '',
        age: '',
        email: ''
    }, //請求參數
    success: function(response, xml) {
        console.log(response); //   此處執行請求成功后的回調
    },
    fail: function(status) {
        console.log('狀態碼為' + status); // 此處為請求失敗后的回調
    }
});


免責聲明!

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



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