您的位置:首页 > 其它

原生Ajax + Promise

2016-05-06 16:34 357 查看
有原生写的ajax + promise嫁接下

;(function(root){
var LD = function(obj){
if( obj instanceof LD ) return obj;
if( !(this instanceof LD )) return new LD(obj);
};

root.LD = LD;

console.log(window.LD);

function __encodeParameter( data ){
let tmp = "";
if(typeof data === 'string')
tmp = data;
else{
var e = encodeURIComponent;
var params = [];
for( let k in data ){
if(data.hasOwnProperty( k )){
params.push( e(k)) +'=' + e(data[k]);
}
}

tmp = params.join('&') ; //
}

return tmp;
}

function __initialize_xhr(){
let xhr ;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}catch(ex){
console.log(ex);
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}

return xhr;
}

var ajax = LD.Ajax = function( method , url , data , headers ,cb){
let promise = new Promise(function(resolve , reject ){
let xhr , params;
data = data || {};
headers = headers || {};

try{
xhr  =  __initialize_xhr();
}catch(ex){
console.log(ex);
}

params = __encodeParameter( data );
console.log("-------"+   params);

if(method == 'GET' && params ){
url += '?' + params;
params = null;
}

xhr.open( method , url );
var content_type = 'application/x-www-form-urlencoded';
for(var h in headers ){
if(headers.hasOwnProperty(h)){
if(h.toLowerCase() === "content-type"){
content_type = headers[h];
}else{
xhr.setRequestHeader(h , headers[h]);
}
}
}

xhr.setRequestHeader('Content-type', content_type );
xhr.onreadystatechange  = function(){
if(xhr.readyState === 4 ){
var err = (!xhr.status || (xhr.status < 200 || xhr.status >= 300) &&
xhr.status !== 304 );
if( err === false ){
resolve( xhr.responseText , xhr );
}else{
reject( err , xhr );
}
//cb(err, xhr.responseText,xhr );
}
};

xhr.send(params);
});

return promise;
};
})(window);


使用

LD.Ajax("GET","/refresh",null,null).then(function(data){
console.log(data);
},function( dt) {
console.log("err:" + dt );
}).catch(function(){
console.log('catch error');
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: