Ajax类应用示例代码
来源:互联网 发布:51duino源码 编辑:程序博客网 时间:2024/05/17 21:30
- Ajax = function(config)
- {
- this._xmlHttpRequest = null;
- this._userConfig = config;
- this._config = {
- method: 'get',
- async: true,
- returnDataFormat: 'jsCode',
- url: null,
- onComplete: function(data){}
- };
- this._init = function()
- {
- if (window.XMLHttpRequest) {
- this._xmlHttpRequest = window.XMLHttpRequest;
- }
- else {
- this._xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
- }
-
- };
-
- this.doRequest = function()
- {
- var instance = this;
- if (!this._xmlHttpRequest) {
- this._init();
- }
- if (this._userConfig) {
- for (var key in this._userConfig) {
- this._config[key] = this._userConfig[key];
- }
- }
- this._xmlHttpRequest.open(this._config.method, this._config.url, this._config.async);
- this._xmlHttpRequest.onreadystatechange = function()
- {
- if (instance._xmlHttpRequest.readyState == 4){
- if (instance._xmlHttpRequest.status == 200){
- var responseText = instance._xmlHttpRequest.responseText;
- if (instance._config.returnDataFormat == 'jsCode') {
- instance._config.onComplete(eval('(' + responseText + ')'));
- }
- else if (instance._config.returnDataFormat == 'string') {
- instance._config.onComplete(responseText);
- }
- else if (instance._config.returnDataFormat == 'xml'){
- instance._config.onComplete(instance._xmlHttpRequest.responseXml);
- }
- }
- }
-
- };
- instance._xmlHttpRequest.send(null);
- }
- }