原生js 的ajax封裝

/** * 封裝ajax函數(包括跨域) * @method  ajax * @param   option :{type:"post" or  "get" 請求方式,url:"url" 請求地址,data:object 請求參數,async:"true" 異步or「false」同步,success:function 請求成功回調函數,error:function,請求失敗函數,jsonp:"true" 表示跨域 「false」:表示不跨域;callback:function  跨域請求函數名} * @return {} * */function ajax(option) {    "use strict";    //檢測傳入參數是不是一個對象    if ({}.__proto__.toString.call(option) !== "[object Object]") {        alert("參數格式錯誤!!");        return;    }    var data = option.data || "";    var async = option.async || "true";//默認是異步    var jsonp = option.jsonp || "false"//默認是不跨域http    var params=[];    var postData;    var getHttpRequest = function () {        if (window.XMLHttpRequest) {            //主流瀏覽器提供了XMLHttpRequest對象            return new XMLHttpRequest();        } else if (window.ActiveXObject) {            //低版本的IE瀏覽器沒有提供XMLHttpRequest對象            //因此必須使用IE瀏覽器的特定實現ActiveXObject            return new ActiveXObject("Microsoft.XMLHttpRequest");        }    };    if(data!==""){        for (var key in data) {            params.push(key + '=' + data[key]);        }    }    postData= params.join('&'); if (jsonp !== "true") {//不是跨域        var httpRequest = getHttpRequest();        if (option.type.toUpperCase() === 'POST') {            httpRequest.open(option.type, option.url, async);            httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');             httpRequest.send(postData);        }   else if (option.type.toUpperCase() === 'GET') {            httpRequest.open(option.type, option.url + '?' + postData, async);            httpRequest.send(null);        }        httpRequest.onreadystatechange=function(){            if(httpRequest.readyState==="4"&&httpRequest.state==="200"){                    option.success(httpRequest.responseTest);            }else{                    option.error(httpRequest.responseTest);            } }    } else {        //跨域        var responseContainer;        var overwritten;        var doc=document.body;        var  _script=document.createElement("script");        _script.setAttribute("type","text/javascript");        _script.src=option.url+"?"+postData+"&callback="+option.callback;        doc.appendChild(_script);        overwritten=window[option.callback];        window[option.callback]=function(){             responseContainer= arguments;        }        option.success(responseContainer[0]);        responseContainer = overwritten = undefined;    }}
相關文章
相關標籤/搜索