【问题标题】:AJAX call within Javascript class (prototype function)Javascript 类中的 AJAX 调用(原型函数)
【发布时间】:2014-10-08 03:27:14
【问题描述】:

我正在实现一个 Javascript 类,但我无法正常工作。 在初始化该类的一个实例后,我调用该类的一个方法,该方法发出 AJAX 请求。然后需要将 AJAX 函数“成功”返回的数据设置为该实例的 a 属性。当我稍后在我的代码中输出 this.results 变量时,它不应该是空的。这是我的代码:

//Individual Member Class
function GetReports(options) {  
    this.options = options;
    this.results = {};
}

GetReports.prototype.getResults = function() {
    jQuery.ajax({
        type      :  'post',
        dataType  :  'json',
        url       :  'reporting/getStaffMemberReports',
        async     :  false,
        data      :  options,
        success   :  function(data) {
            this.results = data;
            setResult(this.results);
        }
    }); 
}

GetReports.prototype.returnResults = function(type) {   
    if(type === "JSON") {       
        JSON.stringify(this.results);
    } else if (type === "serialize") {
        this.results.serialize();
    }
return this.results;
};

GetReports.prototype.setResult = function(data) {
    this.results = data;
};

还有我创建“类”实例的代码:

var jsonString = <?php echo json_encode($JSONallocatedStaffMembers); ?>;
    options = {
        all     : true,
        members : JSON.parse(jsonString),
        type    : 'highperform'
    };
    var all = new GetReports(options);
    all.getResults();
    var results = all.returnResults("JSON");
    console.log(results);

现在,由于 AJAX 调用是异步的,我在想这可能是问题所在?我试过把'async:false'放进去,但这没有帮助。 谁能看出我哪里出错了?

【问题讨论】:

    标签: javascript jquery ajax oop


    【解决方案1】:

    这里有一个问题需要解决。

    this

    内部 ajax 回调是指 ajax 对象,而不是你的 GetReport 实例。您必须在 getResults 上声明一个 var 并指向 在制作 ajax 之前,它会这样做。

    GetReports.prototype.getResults = function() {
        var self = this;
        jQuery.ajax({
            type      :  'post',
            dataType  :  'json',
            url       :  'reporting/getStaffMemberReports',
            async     :  false,
            data      :  options,
            success   :  function(data) {
                self.results = data;
                setResult(self.results);
            };
        }); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多