【发布时间】:2019-10-21 22:46:56
【问题描述】:
在完成 ajax 请求后获得两个整数后,this.N 和 this.M 不会被 storeDims() 设置,即使 dims 已正确解码。所以似乎我无法访问构造函数中声明的this.N 和this.M。
这是代码
class MapModel {
constructor() {
this.N; // need to initialize this after an ajax call
this.M;
this.seats = new Array();
this.remote_seats = new Array();
}
init(callback) {
let _this = this;
$.when(
_this.getDims(),
_this.getSeats(),
).then(this.initMap(callback))
}
initMap(callback) {
console.log(this.N); // prints undefined
console.log(this.M); // this as well
callback(this.N, this.M, this.seats);
}
getDims() {
let _this = this;
$.ajax({
url: 'src/php/data.php',
type: 'POST',
data: {action: 'getDims'},
success: function (result) {
let dims = JSON.parse(result); // dims[0] = 10, dims[1] = 6
_this.storeDims(dims);
}
});
}
storeDims(dims) {
console.log(dims);
this.N = parseInt(dims[0]);
this.M = parseInt(dims[1]);
console.log(this.N);
console.log(this.M);
}
getSeats() {
let _this = this;
$.ajax({
url: 'src/php/data.php',
type: 'POST',
data: {action: 'getSeats'},
success: function (result) {
let seats = JSON.parse(result);
_this.storeSeats(seats);
}
});
}
storeSeats(seats) {
this.remote_seats = seats;
console.log(this.remote_seats);
}
}
【问题讨论】:
-
您的控制台中是否有日志
console.log(dims);? -
@madalinivascu 是的:
(2) […] 0: 10 1: 6 length: 2 <prototype>: Array [] -
在下面查看我的答案
标签: javascript jquery ajax class