Gau*_*ier 2 javascript ajax jquery asynchronous object
抱歉复制但我可以在其他帖子中找到任何解决方案.
我正在尝试使用ajax调用web服务来填充javascript对象.我不明白这个的逻辑以及为什么我的对象在调用后没有设置.我写了这个小例子来解释我的问题:
代码:
function Cellule(){
this.test = 0;
this.textfunction();
}
Cellule.prototype.textfunction = function(){
this.test = 1;
$.ajax({
type: "GET",
url: "BASEURL/cellules",
data: "",
success: function(msg){
console.log("success");
this.test = 2;
console.log(cellule);
}
});
};
var cellule = new Cellule();
Run Code Online (Sandbox Code Playgroud)
控制台出:
success
Cellule {test: 1}
Run Code Online (Sandbox Code Playgroud)
this没有提到cellule
该bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值
或者指定context: this将使用cellule成功处理程序的上下文.
试试这个:
function Cellule() {
this.test = 0;
this.textfunction();
}
Cellule.prototype.textfunction = function() {
this.test = 1;
$.ajax({
type: "GET",
url: "../slimrest/andon/cellules",
data: "",
success: function(msg) {
console.log("success");
this.test = 2;
console.log(cellule);
}.bind(this)
});
};
var cellule = new Cellule();Run Code Online (Sandbox Code Playgroud)