JavaScript类财产Ajax调用成功,函数没有设置 [英] javascript class property not set in success function of ajax call
问题描述
的很抱歉的重复,但我可以找到其他职位的任何解决方案。的
我试图填补使用Ajax调用webservice的JavaScript对象。我不明白这个逻辑,为什么我的对象调用后未设置。我写了这个小例子来解释我的问题:
code:
函数CELLULE(){
this.test = 0;
this.textfunction();
}Cellule.prototype.textfunction =功能(){
this.test = 1;
$阿贾克斯({
键入:GET,
网址:BASEURL / cellules
数据:,
成功:函数(MSG){
的console.log(成功);
this.test = 2;
的console.log(小细胞);
}
});
};VAR小细胞=新CELLULE();
控制台出来:
成功
CELLULE {测试:1}
这个
不引用小细胞
块引用>使用
.bind( )
或背景
在AJAX
设置参数的的
绑定()
方法创建一个新的函数,调用它时,有该关键字设置为提供的值的或指定
背景:该
将在成功处理程序使用小细胞
上下文试试这个:
\r\r\r\r函数CELLULE(){\r
this.test = 0;\r
this.textfunction();\r
}\r
\r
Cellule.prototype.textfunction =功能(){\r
this.test = 1;\r
$阿贾克斯({\r
键入:GET,\r
网址:../slimrest/andon/cellules\r
数据:,\r
成功:函数(MSG){\r
的console.log(成功);\r
this.test = 2;\r
的console.log(小细胞);\r
} .bind(本)\r
});\r
};\r
\r
VAR小细胞=新CELLULE();\r
Sorry for the duplication but I can find any solution in the others posts.
I'm trying to fill a javascript object using a ajax call to a webservice. I don't understand the logic of this and why my object in not set after the call. I wrote this little example to explain my problem :
Code :
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();
Console out :
success Cellule {test: 1}
解决方案
this
does not refer tocellule
Use
.bind()
orcontext
in argument ofajax
settingsThe
bind()
method creates a new function that, when called, has its this keyword set to the provided valueOr specifying
context: this
will use context ofcellule
in success handler.Try this:
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();
这篇关于JavaScript类财产Ajax调用成功,函数没有设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!