Ajax的封装

本文详细解析了AjaxRequest构造函数的实现方式,包括构造函数的参数、内部对象初始化、请求方法的选择以及如何处理请求状态变化,旨在帮助开发者深入理解AJAX请求的底层实现。
var net = new Object();
// AjaxRequest对象的构造函数
net.AjaxRequest = function (method, url, params, onload) {
    this.xmlhttp = null;
    this.onload = onload;
    this.loadData(method, url, params);
}
net.AjaxRequest.prototype.loadData = function (method, url, params) {
    if (!method) {
        method = "GET";
    }
    if (window.XMLHttpRequest) {
        this.xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (this.xmlhttp) {
        try {
            var loader = this;
            this.xmlhttp.open(method, url, true);
            if (method == "POST") {
                this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            this.xmlhttp.onreadystatechange = function () {
                net.AjaxRequest.onStateChange.call(loader);
            }
            this.xmlhttp.send(params);
        } catch (e) {
            this.onerror.call(this);
        }
    }
}

// 重构回调函数
net.AjaxRequest.onStateChange = function () {
    if (this.xmlhttp.readyState == 4) {
        if (this.xmlhttp.status == 200) {
            this.onload.call(this);
        } else {
            this.onerror.call(this);
        }
    } else {
        this.onload.call(this);
    }
}


 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值