将oject的方法传递给ajax - 仅限javascript

时间:2012-12-12 08:09:13

标签: javascript ajax

我有一个对象有两个方法,如下所示:

function PendingRequests(){
    this.count;
    this.id = [];
    this.event = [];
}
PendingRequests.prototype.get = function(){
    var request_parameter = 'cont=pr';
    Ajax(url,request_parameter,this.get2);
}
PendingRequests.prototype.get2 = function(pr){
    this.count = pr.length;
    for(var i=0;i<this.count;i++){
        this.id[i]          = pr[i]['id'];
        this.event[i]       = pr[i]['event'];
    }
}
var pendingrequests = new PendingRequests();

和ajax函数

Ajax(url,parameter,funct){...}

在获得响应后调用传递的函数

funct(JSON.parse(XMLHttpRequestObject.responseText));

脚本执行直到在ajax响应之后调用该方法,但后来我得到“this.id未定义”的错误

请帮忙解决这个问题。

2 个答案:

答案 0 :(得分:0)

您必须为函数分配一个上下文,否则它将在全局上下文中调用,您必须接受ajax函数中的另一个参数:

Ajax(url,parameter,funct, context){...}

然后使用call:

触发该函数
funct.call(context, JSON.parse(XMLHttpRequestObject.responseText));

然后get函数中的调用将是:

Ajax(url,request_parameter,this.get2, this);

答案 1 :(得分:0)

嘿,我尝试了两种建议,但仍然遇到同样的错误。

最后我解决了这个问题。

我做了改变,伊恩建议。 (即使ajax函数也会处理其他对象,但对于所有这些对象我都可以定义一个get2方法)

由于它仍然给出错误,我定义了所有属性:

this.count;
this.id = [];
this.event = [];

以不同的方式:

PendingRequests.prototype.count = 0;
PendingRequests.prototype.id = [];
PendingRequests.prototype.event = [];

现在它正在工作......我将只有一个PendingRequests对象,所以希望原型设计不会在以后给我任何错误。