当前位置: 代码迷 >> Ajax >> 一个简略的AJAX类
  详细解决方案

一个简略的AJAX类

热度:217   发布时间:2012-10-06 17:34:01.0
一个简单的AJAX类
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax类</title>
<script type="text/javascript">
function xStr(s) {
    for (var i = 0; i < arguments.length; ++i) {
        if (typeof (arguments[i]) != 'string') return false
    }
    return true
}
var ylib = function() {
    return {
        util: {},
        widget: {},
        namespace: function(sNameSpace) {
            if (!xStr(sNameSpace)) return null;
            var levels = sNameSpace.split('.');
            var thisNameSpace = ylib;
            for (var i = (levels[0] == 'ylib' ? 1: 0); i < levels.length; i++) {
                thisNameSpace[levels[i]] = thisNameSpace[levels[i]] || {};
                thisNameSpace = thisNameSpace[levels[i]];
            }
        }
    };
} ();
ylib.namespace('ylib.util');
ylib.util.READY_STATE_UNINITIALIZED = 0;//还未被初始化
ylib.util.READY_STATE_LOADING = 1;//准备加载
ylib.util.READY_STATE_LOADED = 2;//正在加载
ylib.util.READY_STATE_INTERACTIVE = 3;//验证
ylib.util.READY_STATE_COMPLETE = 4;//完成
ylib.util.AjaxLib = function (url, callBackHandler, errorHandler, method, params, contentType) {
    this.url = url;
    this.callBackHandler = callBackHandler;
    this.errorHandler = (errorHandler) ? errorHandler : this.DefaultErrorHandler;
    this.method = (method) ? method : 'GET';
    this.params = (params) ? params : [];
    this.contentType = contentType;
    if (!contentType && method == "POST") {
        this.contentType = 'application/x-www-form-urlencoded';
    }
};
ylib.util.AjaxLib.prototype = {
    SendRequest: function () {
        var request = this.getHTTPObject();
        if (request) {
            var requestParams = [];
            for (var i = 0; i < arguments.length; i++) {
                requestParams.push(arguments[i]);
            }
            var loader = this;
            var url = this.url;
            if (this.method == 'GET' && requestParams.length > 0) {
                var qs = this.GetFullQuerystring(requestParams);
                if (qs) {
                    if (url.indexOf('?') == -1) {
                        url += '?' + qs;
                    } else {
                        url += '&' + qs;
                    }
                }
            }
            try {
                request.onreadystatechange = function () {
                    loader.HandleAjaxResponse.call(loader, request);
                };
                request.open(this.method, url, true);
                if (this.contentType) request.setRequestHeader('Content-Type', this.contentType);
                request.setRequestHeader('encoding', 'UTF-8');
                if (this.method == 'GET') {
                    request.send(null);
                } else {
                    request.send(this.GetFullQuerystring(requestParams));
                }
            } catch (err) {
                loader.error = err;
                this.errorHandler.call(loader, request);
            }
        }
    },
    getHTTPObject: function () {
		var http;
		var browser = navigator.appName;
		if(browser == "Microsoft Internet Explorer"){
			http = new ActiveXObject("Microsoft.XMLHTTP"); 
		}else{
			http = new XMLHttpRequest(); 
		}
		return http;
    },
    GetFullQuerystring: function (args) {
        var requestParams = [];
        for (var i = 0; i < this.params.length; i++) {
            if (this.params[i]) requestParams.push(this.params[i]);
        }
        for (var i = 0; i < args.length; i++) {
            if (args[i]) requestParams.push(args[i]);
        }
        var qs = "";
        if (requestParams && requestParams.length > 0) {
            qs = requestParams.join("&");
        }
        return qs;
    },
    HandleAjaxResponse: function (request) {
        var loader = this;
        if (request.readyState == ylib.util.READY_STATE_COMPLETE) {
            if (loader.RequestSuccess(request)) {
                loader.callBackHandler.call(loader, request);
            } else {
                loader.errorHandler.call(loader, request);
            }
            request = null;
        }
    },
    RequestSuccess: function (request) {
        return request.status == 0 || (request.status >= 200 && request.status < 300);
    },
	DefaultErrorHandler : function (request) {
		var mess = "请求发送失败!";
		if (this) {
			if (this.url) mess += "\n\nurl:" + this.url;
			if (this.method) mess += "\n\nmethod:" + this.method;
			if (this.contentType) mess += "\n\ncontentType:" + this.contentType;
			if (this.params) mess += "\n\nparams:" + this.params;
			if (this.error) {
				if (this.error.name) mess += "\n\nerror name:" + this.error.name;
				if (this.error.message) mess += "\n\nerror message:" + this.error.message;
			}
		}
		if (request) {
			if (request.readyState) mess += "\n\nreadyState:" + request.readyState;
			try {
				if (request.status) mess += "\n\nstatus:" + request.status;
			} catch (err) {}
			try {
				if (request.getAllResponseHeaders) mess += "\n\nheaders:" + request.getAllResponseHeaders();
			} catch (err) {}
		}
		alert(mess);
	}
};

<!--调用方式-->
var lib = new ylib.util.AjaxLib("t.jsp",createAjaxCallBack,"","POST");
function creatAjax(){
	lib.SendRequest("a=123452","v=12312");	
}

function createAjaxCallBack(request){
	var jsonArray = request.responseText;
	alert(jsonArray)	
}
</script>

</head>
<body>
<input type="button" value="创建AJAX请求" onclick="creatAjax()" />
</body>
</html>
  相关解决方案