jQuery对象、不一致的全局变量和AJAX调用

jQuery object, inconsistent global variables and AJAX call

本文关键字:AJAX 调用 全局变量 对象 不一致 jQuery      更新时间:2023-09-26

我想得到一个我认为简单的脚本来运行AJAX调用并将各种值存储到对象中,但我无法使全局变量保持我期望的一致性。

我绕了一圈,尝试我认为的一切。一旦我加入AJAX调用,我就无法让它很好地处理全局变量。process的值始终是false,并且内容永远不会加载到中

ExtContent = function(){
    var self = this;
    this.init = function() {
        self.output = null;
        self.process = false;
    };
    this.request = function(url){
        $.ajax({
            type     : 'GET',
            timeout  : 10000,
            dataType : 'html',
            url      : url,
            passself : self,
            success  : function(response){
                this.passself.setoutput(response);
            },
            error    : function(req,response){
                if(response==='error'){
                    self.error=req.statusText;
                }
            }
        });
    };
    this.setoutput = function(data){
        this.output = data;
        this.process = true;
    };
    this.returnprocess = function(){
        return self.process;
    };
    this.returnoutput = function(){
        return self.output;
    };
    self.init();
};

<div id="holder"></div>

loadcontent = new ExtContent(); 
loadcontent.request('/test.html');
if(loadcontent.returnprocess()){
    $('#holder').before(loadcontent.returnoutput());
}else{
    $('#holder').before('FAILED');
}

我无法将process设为true,也无法将内容存储在output中。

谢谢。

尽管将所有内容包装为类/对象,jQuery $.ajax调用仍然是异步操作。基本上是"你点了一个披萨,然后试着在它到达之前把它吃掉"。

即此订单:

loadcontent.request('/test.html');

它试图立即吃掉它:

if(loadcontent.returnprocess()){

呼叫setoutput(即"披萨配送")发生在这些操作完成很久之后。

您需要将事件处理程序属性添加到类中,或者使用deferreds+promise来等待数据到达。

要使用promise,只需从request:返回$.ajax结果

this.request = function(url){
    return $.ajax({
        type     : 'GET',
        timeout  : 10000,
        dataType : 'html',
        url      : url,
        passself : self,
        success  : function(response){
            this.passself.setoutput(response);
        },
        error    : function(req,response){
            if(response==='error'){
                self.error=req.statusText;
            }
        }
    });
};

并像这样使用:

loadcontent.request('/test.html').done(function(){
    if(loadcontent.returnprocess()){
        $('#holder').before(loadcontent.returnoutput());
    }else{
        $('#holder').before('FAILED');
    }
 });

或者,如果您在请求中正确设置了返回值:

loadcontent.request('/test.html').done(function(){
    $('#holder').before(loadcontent.returnoutput();
}).fail(function(){
    $('#holder').before('FAILED');
});

也许这可以帮助您

this.setoutput = function(data){
    // 'this' here, is refering 'setoutput' function, not ExtContent,
    // so ExtContent.process != ExtContent.setoutput.process
    // this.output = data;
    // this.process = true;
    self.output = data;
    self.process = true;
};