0

私は小さな JavaScript ユーティリティ ライブラリを作成しています。その主な要件は、次のメソッドです。

  • URL と ID を受け取ります
  • これらのパラメーターを使用して、(提供された URL から) Ajax によってコンテンツを取得し、それを (ID で指定された) HTML 要素に配置します。

私が取っているアプローチは次のとおりです。

  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

*更新*

これを行う:

これをあなたの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 に答える
0

たとえばAjaxSuccess、 と など、2 つの追加のハンドラを作成しますAjaxError。その後、をパラメータとしてAjaxSuccessから呼び出すことができます。また、ハンドラーをバインドするときに、ターゲット DOM 要素をパラメーターとして追加します。ajaxReadyStateHandlerresponseText

jQueryZeptoのソース コードを調べて、それらがどのように処理されているかを確認してみませんか? または、実績のあるフレームワークであるこれらのライブラリを使用しない理由はありますか?

于 2012-11-10T16:07:08.210 に答える