码迷,mamicode.com
首页 > Web开发 > 详细

原生ajax类

时间:2018-04-30 19:56:36      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:原生ajax类

  • 代码:
    /*
    @desc ajax请求类
    @author lee [<complet@163.com>]
    @param data object
    {
    data        # 发送到后台的数据,支持json和表单
    url         # 请求的接口地址
    type        # 请求方式 get或post
    async       # 同步或异步 true:异步 false:同步
    json        # 发送的数据是否是json还是表单 true:json false:表单
    auth        # 后台授权验证 默认为空
    }
    */
    function ajax(){
    this.xhr
    this.data
    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){
                func()
            }
        })
        return this
    }
    this.request = function(obj){
        this.data = obj.data
        var url = obj.url
        var type = obj.type
        var async = obj.async
        var json = (obj.json===true)?true:false
        var auth = obj.auth
        this.init()
        this.xhr.open(type,url,async)
        if(json){
            this.xhr.setRequestHeader("Content-type", "application/json")
            this.data = JSON.stringify(this.data)
        }else{
            this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        }
        if(auth){
            this.xhr.withCredentials = true
            this.xhr.setRequestHeader("Authorization", "Basic " + btoa(auth))
        }
        return this
    }
    this.send = function(){
        this.xhr.send(this.data)
    }
    }
  • 用法:
    var xhr = new ajax()
    var data = {
    data:‘name=lee‘,
    url:‘http://localhost/test.php‘,
    type:‘post‘,
    async:true,
    json:false
    }
    xhr.request(data).before(function(){
    console.log(1)
    }).success(function(data){
    console.log(data)
    }).error(function(){
    console.log(2)
    }).send()
  • 效果:
    技术分享图片
  • 原生ajax类

    标签:原生ajax类

    原文地址:http://blog.51cto.com/12173069/2109281

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!