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);
}
}
本文详细解析了AjaxRequest构造函数的实现方式,包括构造函数的参数、内部对象初始化、请求方法的选择以及如何处理请求状态变化,旨在帮助开发者深入理解AJAX请求的底层实现。
523

被折叠的 条评论
为什么被折叠?



