0

我正在编写一个小型 JavaScript 实用程序库,其关键要求是一种方法:

  • 获取 URL 和 ID
  • 使用这些参数通过 Ajax(从提供的 URL)获取内容并将其放入 HTML 元素(由 ID 指定)。

我采取的方法是:

  1. 创建一个对象来命名库 [不是直接相关,但它确实解释了下面代码的结构]
  2. 编写基于传递给它的 URL 返回 ajax 内容的通用方法 [请求工作正常,但将内容提供给单独的函数是我遇到问题的地方]
  3. 编写一个通用方法,该方法将采用 ajax 方法并将返回的值放入指定的 HTML 元素中[我希望这将非常简单,如果我能解决第 2 点]

我的问题是,当 onreadystatechange 确定 readyState 为 4 时,我无法找到返回内容的方法。发生这种情况时,我需要能够将 this.returnText 的值传递给一个将其放入HTML。

相关代码如下(完整包含,但最相关的部分包含在注释中

// Init-time branching is used to detect objects and set functions accordingly.
var utilite = {
    addListener: null,
    removeListener: null,
    createAjaxObject: null,
    ajaxReadyStateHandler: function() {
          console.log('Ready state is: ' + this.readyState);
          if (this.readyState === 4) {
              // Check the status code:
              if ( (this.status >= 200 && this.status < 300) || (this.status === 304) ) {
                console.log('Status OK');
                if(this.status === 304){
                    console.log('Using cached version');
                }
                // Here's the problem: 
                // Despite 'testingAjax' being passed to the original calling function
                // I can't access it directly and am forced to hard-code it here.
                utilite.setElementContent({id: 'testingAjax', content: this.responseText});
              } else { // Status error!
                console.log('Status error: ' + this.statusText);
              }
          } // End of readyState IF.
      },
    doAjax: function(passedObject) {
    var ajax = utilite.createAjaxObject();
    ajax.onreadystatechange = utilite.ajaxReadyStateHandler;
    ajax.open(passedObject.requestType, passedObject.resource, true);
    ajax.send(null);
    },
    getElement: function (id) { // Retrieves element by passed id
        'use strict';
        if (typeof id == 'string') {
            return document.getElementById(id);
        }
    },
    setElementContent: function(passedObject){
        'use strict';
        var theElement = utilite.getElement(passedObject.id);
        theElement.textContent = passedObject.content;
    }
}; // This is the end of utilite

// Event listener branches
if (typeof window.addEventListener === 'function') { // W3C and IE9
    utilite.addListener = function (obj, type, fn) {
        obj.addEventListener(type, fn, false);
    };
    utilite.removeListener = function (obj, type, fn) {
        obj.removeEventListener(type, fn, false);
    };
} else if (typeof document.attachEvent === 'function') { // IE
    utilite.addListener = function (obj, type, fn) {
        obj.attachEvent('on' + type, fn);
    };
    utilite.removeListener = function (obj, type, fn) {
        obj.detachEvent('on' + type, fn);
    };
} else { // DOM Level 0
    utilite.addListener = function (obj, type, fn) {
        obj['on' + type] = fn;
    };
    utilite.removeListener = function (obj, type, fn) {
        obj['on' + type] = null;
    };
}

// Ajax object creation branches
utilite.createAjaxObject = function() {
    var ajax = null;
    if(window.XMLHttpRequest){
        ajax = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // Older IE.
        ajax = new Ac
    var utilite = {
        addListener: null,
        removeListener: null,
        createAjaxObject: null,
        ajaxReadyStateHandler: function() {
              if (this.readyState === 4) {
                  if ( (this.status >= 200 && this.status < 300) || (this.status === 304) ) {
                    if(this.status === 304){
                        console.log('Using cached version');
                    }
                  /* -------------------------

                  It is the value of this.responseText here that I need to provide to a separate function

                  */ -------------------------
                  } else { // Status error!
                    console.log('Status error: ' + this.statusText);
                  }
              } // End of readyState IF.
          },
        doAjax: function(passedObject) {
        var ajax = utilite.createAjaxObject();
        ajax.onreadystatechange = utilite.ajaxReadyStateHandler;
        ajax.open(passedObject.requestType, passedObject.resource, true);
        ajax.send(null);
        },
        getElement: function (id) { // Retrieves element by passed id
            'use strict';
            if (typeof id == 'string') {
                return document.getElementById(id);
            }
        }
    }; // This is the end of utilite
    // Event listener branches
    if (typeof window.addEventListener === 'function') { // W3C and IE9
        utilite.addListener = function (obj, type, fn) {
            obj.addEventListener(type, fn, false);
        };
        utilite.removeListener = function (obj, type, fn) {
            obj.removeEventListener(type, fn, false);
        };
    } else if (typeof document.attachEvent === 'function') { // IE
        utilite.addListener = function (obj, type, fn) {
            obj.attachEvent('on' + type, fn);
        };
        utilite.removeListener = function (obj, type, fn) {
            obj.detachEvent('on' + type, fn);
        };
    } else { // DOM Level 0
        utilite.addListener = function (obj, type, fn) {
            obj['on' + type] = fn;
        };
        utilite.removeListener = function (obj, type, fn) {
            obj['on' + type] = null;
        };
    }
    // Ajax object creation branches
    utilite.createAjaxObject = function() {
        var ajax = null;
        if(window.XMLHttpRequest){
            ajax = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // Older IE.
            ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        return ajax;
    };
    init = function(){
        utilite.doAjax({requestType: 'GET', resource: 'test.txt'});
    };
    utilite.addListener(window, 'load', init);
tiveXObject('MSXML2.XMLHTTP.3.0');
    }
    return ajax;
};

init = function(){
    utilite.doAjax({requestType: 'GET', resource: 'test.txt', target: 'testingAjax'});
};

utilite.addListener(window, 'load', init);

任何和所有的帮助将不胜感激。

谢谢

4

3 回答 3

0

我将创建两个额外的处理程序,例如AjaxSuccessAjaxError. 然后,您可以AjaxSuccess从调用作为参数。在绑定处理程序时还要添加目标 DOM 元素作为参数。ajaxReadyStateHandlerresponseText

为什么不查看jQueryZepto的源代码,看看它们是如何处理这些事情的呢?或者为什么不使用这些库,它们是经过验证的框架?

于 2012-11-10T16:07:08.210 回答
0

*更新*

做这个:

把它放在你的ajax之外:

this.funcResp= function(resp){ console.log(resp) };
var thisObj=this;

把它放在你的 ajax 函数中:

thisObj.funcResp(responseText); 
于 2012-11-10T16:29:15.947 回答
0

再次感谢您的回复。我现在已经设法使用范围解决了这个问题。就是这样:

  1. 向名为 elementToUpdate 的命名空间对象添加了一个属性。
  2. 让 doAjax() 函数更改 elementToUpdate 的值。
  3. 从 ajaxReadyStateHandler() 引用 elementToUpdate。

这很好用,但在重复调用 doAjax() 时确实会出现一些问题。我怀疑这是因为 elementToUpdate 被反复引用/更新。下次我会解决这个问题。

再次感谢。代码如下所示。G

// Init-time branching is used to detect objects and set functions accordingly.

    var utilite = { 
    addListener: null,
    removeListener: null,
    createAjaxObject: null,
    elementToUpdate: null,
    ajaxReadyStateHandler: function() {
          console.log('Ready state is: ' + this.readyState);
          if (this.readyState === 4) {
              // Check the status code:
              if ( (this.status >= 200 && this.status < 300) || (this.status === 304) ) {
                console.log('Status OK');
                if(this.status === 304){
                    console.log('Using cached version');
                }
                // Note: elementToUpdate is accessible here because of the way scope works
                utilite.setElementContent({id: elementToUpdate, content: this.responseText});
              } else { // Status error!
                console.log('Status error: ' + this.statusText);
              }
          } // End of readyState IF.
      },
    doAjax: function(passedObject) {
    elementToUpdate = passedObject.target;
    var ajax = utilite.createAjaxObject();
    ajax.onreadystatechange = utilite.ajaxReadyStateHandler;
    ajax.open(passedObject.requestType, passedObject.resource, true);
    ajax.send(null);
    },
    getElement: function (id) { // Retrieves element by passed id
        'use strict';
        if (typeof id == 'string') {
            return document.getElementById(id);
        }
    },
    setElementContent: function(passedObject){
        'use strict';
        var theElement = utilite.getElement(passedObject.id);
        if(typeof theElement.innerText !== 'undefined') { theElement.innerText = passedObject.content; }
        if(typeof theElement.textContent !== 'undefined') { theElement.textContent = passedObject.content; }
    }
}; // This is the end of utilite

// Event listener branches
if (typeof window.addEventListener === 'function') { // W3C and IE9
    utilite.addListener = function (obj, type, fn) {
        obj.addEventListener(type, fn, false);
    };
    utilite.removeListener = function (obj, type, fn) {
        obj.removeEventListener(type, fn, false);
    };
} else if (typeof document.attachEvent === 'function') { // IE
    utilite.addListener = function (obj, type, fn) {
        obj.attachEvent('on' + type, fn);
    };
    utilite.removeListener = function (obj, type, fn) {
        obj.detachEvent('on' + type, fn);
    };
} else { // DOM Level 0
    utilite.addListener = function (obj, type, fn) {
        obj['on' + type] = fn;
    };
    utilite.removeListener = function (obj, type, fn) {
        obj['on' + type] = null;
    };
}

// Ajax object creation branches
utilite.createAjaxObject = function() {
    var ajax = null;
    if(window.XMLHttpRequest){
        ajax = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // Older IE.
        ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    }
    return ajax;
};

init = function(){
    utilite.doAjax({requestType: 'GET', resource: 'test.txt', target: 'funky'});
};

utilite.addListener(window, 'load', init);
于 2012-11-11T09:16:42.343 回答