代码之家  ›  专栏  ›  技术社区  ›  miki725

AJAX(XMLHTTPRequest)延时

  •  0
  • miki725  · 技术社区  · 15 年前

    我正在创建一个photogallery页面,并在上面创建了一个Javascript类来管理整个事情。下面是类中调用先前成功初始化的XMLHTTPRequest对象的方法:

    this.AJAX_update = function(id) {
        //initialize AJAX - this is done successfully
        this.AJAX_initialize();
        var url = "ScriptLibrary/gallery_update.php?img=" + id;
        //this.ajax_request is an internal variable which is
        //initialized in this.AJAX_initialize() and is
        //XMLHTTPRequest type
        this.ajax_request.open("GET", url, true);
        this.ajax_request.onreadystatechange = processAJAX;
        this.ajax_request.send(null);
    }
    

    我不知道如何在onreadystatechange中调用类的内部方法,所以我在类外部创建了一个函数,该函数调用类内部的方法,前提是该类的实例已在其所在的页上创建。页面上类的实例是变量“gallery”。功能如下:

    function processAJAX() {
        gallery.AJAX_process();
    }
    

    this.AJAX_process = function() {
        if (this.ajax_request.readyState == 4) {
            if (this.ajax_request.status == 200) {
                //get the response
                var response = this.ajax_request.responseXML;
    
                //Here I set the internal variables according to the value
                //returned from the server
                //...........
                //...........
                //...........
    
                //change image on the page
                var self = this;
                setTimeout(function() {
                    self.swap_dissolve();
                }, 50);
    
            }
        }
    }
    

    所以,我的问题是:

    我的代码中任何解决此问题的建议或错误都将非常感谢。

    谢谢您。

    1 回复  |  直到 15 年前
        1
  •  1
  •   user166390 user166390    15 年前

    您想要使用“闭包”(例如,将函数对象传递给setTimeout)。

    想象一下(见鬼,在代码中替换它以查看):

    // when response = 200
    var someValue = "blahblah" // whatever you read in
    setTimeout(function () {
      alert(someValue)
    }, 1000)
    

    这里有一个参考: http://jibbering.com/faq/notes/closures/ 更柔和的介绍: http://blog.morrisjohns.com/javascript_closures_for_dummies.html

    快乐的编码。

    编辑/P.S。

    var self = this
    this.ajax_request.onreadystatechange = function () {
       self.process_AJAX()
    }
    

    你甚至可以用双层装订,但是。。。再次高兴地编码:-)