您现在的位置: 365建站网 > 365文章 > XHR工厂

XHR工厂

文章来源:365jz.com     点击数:242    更新时间:2009-09-14 10:29   参与评论

 

/* XHR工厂 */

/* AjaxHandler interface. */

var AjaxHandler = new Interface('AjaxHandler', ['request', 'createXhrObject']);

/* SimpleHandler class. */

var SimpleHandler = function() {}; //implements AjaxHandler
SimpleHandler.prototype = {
    request: function(method, url, callback, postVars) {
        var xhr = this.createXhrObject();
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) {
                return;
            }
            (xhr.status === 200) ? callback.success(xhr.responseText, xhr.responseXML) : callback.failure(xhr.status);
        };
        xhr.open(method, url, true);
        if (method !== 'POST') {
            postVars = null;
        }
        xhr.send(postVars);
    },
    createXhrObject: function() { //Factory method.
        var methods = [
            function() { return new XMLHttpReques();},
            function() { return new ActiveXObject('Msxml2.XMLHTTP');},
            function() { return new ActiveXObject('Microsoft.XMLHTTP');}
        ];
       
        for(var i = 0, len = methods.length; i < len; i++){
            try{
                methods[i]();
            }catch(e){
                continue;
            }
            // If we reach this point, method[i] worked.
            this.createXhrObject = methods[i]; // Memoize the method.
            throw new Error('SimpleHandler: Could not create an XHR object.');
        }
    }
};

//var myHandler = new SimpleHandler();
//var callback = {
//    success: function(responseText) { alert('Successs: '+ responseText); },
//    failure: function(statusCode) { alert('Failure: '+ statusCode); }
//};

//myHandler.request('GET', 'sctipt.php', callback);


/* QueuedHandler class. */
var QueuedHandler = function() { //implement AjaxHandler
    this.queue = [];
    this.requestInProgress = false;
    this.retryDelay = 5; //In seconds. 
};

extend(QueuedHandler, SimpleHandler);

QueuedHandler.prototype.request = function(method, url, callback, postVars, override) {
    if (this.requestInProgress && !override) {
        this.queue.push({
            method: method,
            url: url,
            callback: callback,
            postVars: postVars
        });
    }else{
        this.requestInProgress =true;
        var xhr = this.createXhrObject();
        var that = this;
        xhr.onreadystatechange = function(){
            if (xhr.readyStatue !== 4) return;
            if (xhr.status === 200) {
                callback.success(xhr.responseText, xhr.responseXML);
                that.advanceQueue();
            }else{
                callback.failure(xhr.status);
                setTimeout(function() { that.request(method, url, callback, postVars, true); }, that.retryDelay * 1000);
            }
        };
        xhr.open(method, url, true);
        if (method !== 'POST') {
            postVars = null;
        }
        xhr.open();
    }
};

QueuedHandler.prototype.advanceQueue = function() {
    if (this.queue.length === 0) {
        this.requestInProgress = false;
        return;
    }
    var req = this.queue.shift();
    this.request(req.method, req.url, req.callback, req.postVars, true);
};


/* OfflineHandler class. */
var OfflineHandler = function() {
    this.storedRequests = [];
};

extend(OfflineHandler, SimpleHandler);

OfflineHandler.prototype.request = function(method, url, callback, postVars) {
    if (XhrManager.isOffline) { //Store the request until we are online.
        this.storeRequest.push({
            method: method,
            url: url,
            callback: callback,
            postVars: postVars
        });
    }else{// Call SimpleHandler's request method if we are online.
        this.flushStoredRequests();
        OfflineHandler.superclass.request(method, url, callback, postVars);
    }
};

OfflineHandler.prototype.flushStoredRequests = function() {
    for(var i = 0, len = storedRequests.length; i < len; i++) {
        var req = storedRequests[i];
        OfflineHandler.superclass.request(req.method, req.url, req.callback, req.postVars);
    }
};

/* XhrManager singleton. */

var XhrManager = {
    createXhrHandler: function() {
        var xhr;
        if (this.isOffline()) {
            xhr = new OfflineHandler();
        }
        else if (this.isHighLatency) {
            xhr = new QueuedHandler();
        }
        else{
            xhr = new SimpleHandler();
        }
       
        Interface.ensureImplements(xhr, AjaxHandler);
        return xhr;
    },
   
    isOffline: function() { // Do a quick request with SimpleHandler and see if it succeeds.
        //...
    },
   
    ifHighLatency: function() { // Do aseries of requests with SimpleHandler and time the response. Best done once, as a branching funciton.
        //...
    }
   
};

//var myHandler = XhrManager.createXhrHandler();
//var callback = {
//    success: function(responseText) { alert('Successs: '+ responseText); },
//    failure: function(statusCode) { alert('Failure: '+ statusCode); }
//};

//myHandler.request('GET', 'sctipt.php', callback);

 

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (242人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号