Ajax总结

2017-04-08  本文已影响0人  赵BW

今天封装了一个简单的ajax。所以顺便总结一下。

#######ajax概念


ajax封装

可以满足基本的需求。后面根据使用情况会一点点更新。

function ajax(opts){
var xhr = new XMLHttpRequest();
var data = '';
for(var key in opts.data){
    data += key + "=" + opts.data[key] + "&";
}
data = data.substring(0,data.length-1);
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
            var result = JSON.parse(xhr.responseText);
            opts.success(result);    
        }else{
            opts.error();
        }
    }
}
if(opts.type == "get"){
    xhr.open("get",opts.url+"?"+data,true);   
    xhr.send();
}
if(opts.type == "post"){
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xhr.open("post",opts.url,true);   
    xhr.send(data);
}
}

调用格式
  ajax({
    url: '/login',   //接口地址
    type: 'get',               // 类型, post 或者 get,
    data: {
        username: 'xiaoming',
        password: 'abcd1234'
    },
    success: function(ret){
        console.log(ret);       // {status: 0}
    },
    error: function(){
       console.log('出错了')
    }
})
上一篇 下一篇

猜你喜欢

热点阅读