为了账号安全,请及时绑定邮箱和手机立即绑定

javascript原生ajax类

标签:
JavaScript

  1. 代码:

    function ajax(){this.xhrthis.datathis.strtojson = function(str){    var arr = str.split('&')    var json = {}    for(var i in arr){        var k = arr[i].split('=')[0]        var v = arr[i].split('=')[1]        json[k] = v    }    return json}this.jsontostr = function(json){    var arr = new Array()    for(var k in json){        var v = json[k]        var val = k+'='+v        arr.push(val)    }    var str = arr.join('&')    return str}this.parseurl = function(url){    var reg = /(?:([A-Za-z]+):)?(\/{0,3})?(?:(.*):(.*)@)?([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?/    var res = reg.exec(url)    var scheme = (res[1])?res[1]:'http'    var user = (res[3])?res[3]:''    var pass = (res[4])?res[4]:''    var host = (res[5])?res[5]:''    var port = (res[6])?res[6]:''    var path = (res[7])?res[7]:''    var query = (res[8])?res[8]:''    var fragment = (res[9])?res[9]:''    var ret = {        scheme:scheme,        host:host,        port:port,        user:user,        pass:pass,        path:path,        query:query,        fragment:fragment    }    return ret}this.init = function(){    if(window.XMLHttpRequest){        this.xhr=new XMLHttpRequest()    }else{        this.xhr=new ActiveXObject("Microsoft.XMLHTTP")    }    return this}this.before = function(func){    this.xhr.addEventListener('readystatechange',function(){        if(this.readyState < 4){            func()        }    })    return this}this.success = function(func){    this.xhr.addEventListener('readystatechange',function(){        if (this.readyState == 4 && this.status == 200){            var res            if(this.getResponseHeader('content-type')==='application/json'){                res = JSON.parse(this.responseText)            }else{                res = this.responseText            }            func(res)        }    })    return this}this.error = function(func){    this.xhr.addEventListener('readystatechange',function(){        if(this.readyState == 4 && this.status != 200){            this.xhr.abort()            func()        }    })    return this}this.progress = function(func){    this.xhr.upload.addEventListener('progress',function(e){        if(e.lengthComputable){            var loading = Math.round(e.loaded / e.total * 100);            func(loading)        }    })    return this}this.request = function(obj){    var data = obj.data    var url = obj.url    var type = obj.type    var async = obj.async    var auth = obj.auth    this.init()    if(type == 'post'){        this.xhr.open(type,url,async)        this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")        if(data instanceof Object){            if(data instanceof FormData){                var obj = {}                data.forEach(function(val,key){                    if((key != 'undefined') && (val != 'undefined')){                        obj[key] = val                    }                })                data = this.jsontostr(obj)            }else{                data = this.jsontostr(data)            }        }    }else if(type == 'get'){        var info = this.parseurl(url)        var scheme = info.scheme        var host = info.host        var path = info.path        var query = info.query        if(data instanceof Object){            if(data instanceof FormData){                var obj = {}                data.forEach(function(val,key){                    if((key != 'undefined') && (val != 'undefined')){                        obj[key] = val                    }                })                data = this.jsontostr(obj)            }else{                data = this.jsontostr(data)            }        }        var psep = (path)?'/':''        var sep = (query || data)?'?':''        url = scheme+'://'+host+psep+path+sep+query+data        data = ''        this.xhr.open(type,url,async)    }else if(type == 'json'){        this.xhr.open('post',url,async)        this.xhr.setRequestHeader("Content-type", "application/json")        if((typeof(data)=='string')||(data instanceof String)){            data = this.strtojson(data)        }else if(data instanceof Object){            if(data instanceof FormData){                var obj = {}                data.forEach(function(val,key){                    if((key != 'undefined') && (val != 'undefined')){                        obj[key] = val                    }                })                data = obj            }        }        data = JSON.stringify(data)    }else if(type == 'file'){        this.xhr.open('post',url,async)        if((typeof(data)=='string')||(data instanceof String)){            return false        }else if(data instanceof Object){            if(!data instanceof FormData){                return false            }        }    }    if(auth){        this.xhr.withCredentials = true        this.xhr.setRequestHeader("Authorization", "Basic " + btoa(auth))    }    this.data = data    return this}this.send = function(){    this.xhr.send(this.data)}}
  2. 用法:

    var ajax = new ajax()var data = {data:'name=lee&sex=male',url:'http://localhost/test.php',type:'post',async:true}ajax.request(data).progress(function(loading){console.log(loading)}).success(function(data){console.log(data)}).error(function(){console.log(2)}).send()


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消