Jim*_*Jim 4 javascript oop ajax jquery
我正在实现一个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;
};
Run Code Online (Sandbox Code Playgroud)
我的代码创建了'class'的实例:
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);
Run Code Online (Sandbox Code Playgroud)
现在,由于AJAX调用是异步的,我认为这可能是问题所在?我尝试过'async:false',但这没有用.任何人都可以看到我错在哪里?
小智 10
这里有一件事需要修复.
该 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);
};
});
}
Run Code Online (Sandbox Code Playgroud)