javascript封装的ajax函数库

下面是封装好的ajax的函数

function AjaxObj() {
    this.xmlHttp = null;
    this.Request = function(method, url, data, callback, sync) {
        if (window.ActiveXObject) {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        } else if (window.XMLHttpRequest) {
            this.xmlHttp = new XMLHttpRequest();
            if (this.xmlHttp.overrideMimeType) {
                this.xmlHttp.overrideMimeType('text/xml');
            }
        }
        if (this.xmlHttp) {
            var self = this;
            if (callback)
                this.xmlHttp.onreadystatechange = function(){callback(self.xmlHttp);};
            else
                this.xmlHttp.onreadystatechange = function(){return;};
            if (!method)
                method = "POST";
            method = method.toUpperCase();
            if (method == 'GET') {
                this.xmlHttp.open('GET', url + ((typeof data=="string")?('?' + data):""), typeof sync == "boolean" ? sync : true);
                this.xmlHttp.send(null);
            } else {
                this.xmlHttp.open('POST', url, typeof sync == "boolean" ? sync : true);
                this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                this.xmlHttp.send(data);
            }
        }
    };
    this.abort = function() {
        if (this.xmlHttp)
            this.xmlHttp.abort();
    };
    this.swRequest = function(cfg){
        if(!cfg.url)
            return;
        this.Request(cfg.method||"POST",cfg.url||"",cfg.data,function(req){
            if(req.readyState==4){
                if(req.status==200||req.status==0){
                     var obj = null;
                     var text = req.responseText;
                     eval("obj = "+ text);
                     cfg.success.call(cfg.soap||this,obj);
                    return;
                }else{
                     cfg.failure.call(cfg.soap||this,"错误!");
                     return;
                }
            }
        });
    };
}
 调用方法:

ajax.swRequest({
    method:"POST",
    sync:false,
    url:'?a=manage&m=checkUser',
    data:"user="+user.value,
    success: function(msg) {
        if(msg==1){
            flag.value = 'true';
        } else {
            flag.value = '';
        }
    },
    failure: function(a) {
        alert(a);
    },
    soap:this
});

本文链接:javascript封装的ajax函数库

联系作者:javascript博客
版权所有:非特殊说明都是本站原创文章,转载请注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值