我正在实现一个 Javascript 类,但我无法开始工作。 在我初始化该类的一个实例之后,我调用该类的一个方法来发出 AJAX 请求。然后需要将 AJAX 函数“成功”返回的数据设置为该实例的属性。当我稍后在我的代码中输出 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,”,但这无济于事。 谁能看出我哪里出错了?
最佳答案
这里要解决一件事。
这个
inside ajax callback refers to ajax object, and not your GetReport instance. You have to declare a var on getResults and point it to this before make the 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);
};
});
}
关于javascript - Javascript 类中的 AJAX 调用(原型(prototype)函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25308711/