[英]Calling Nested Function In Javascript - Is Not Defined Error When Called Within jQuery.ajax.success
I am making an ajax form submission inside an object. 我正在对象内部进行Ajax表单提交。
When I try call the other object methods within the jQuery.ajax.success callback, this line throws an error... 当我尝试在jQuery.ajax.success回调中调用其他对象方法时,此行将引发错误...
Is this a scoping issue? 这是范围问题吗?
this.DisplayError(data.error);
this.DisplayError is not a function this.DisplayError不是函数
Code: 码:
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: function(data) {
if(data.success === false) {
this.DisplayError(data.error);
}
console.log(data); // show response from the php script.
}
});
}
}
Use arrow function: 使用箭头功能:
success: () => {
}
This happens because you are loosing context, Ajax assigns different context when calling success function. 发生这种情况是因为您失去了上下文,调用成功函数时Ajax分配了不同的上下文。 You can also save context in New variable: 您还可以将上下文保存在New变量中:
var self = this;
And use it inside success function instead of this. 并在成功函数内使用它来代替它。 Or you can define function context: 或者,您可以定义函数上下文:
success: (function() {
}).bind(this)
this
inside the success function is not equal to this
outside. this
成功函数内部不等于this
之外。 The simplest way to handle this is using arrow function. 解决此问题的最简单方法是使用箭头功能。
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: data => {
if(data.success === false) {
this.DisplayError(data.error); // now `this` should be equal to the one outside
}
console.log(data); // show response from the php script.
}
});
}
}
The magic is, arrow function does not has its own this
. 魔术是,箭头功能没有它自己的this
。 When you call this
, it will refer to the outside one. 当你调用this
,它会参考一个以外。 But normal function has its own this
, therefore when you call this
, it will refer to its own this
instead of the outside one. 但是普通函数有它自己的this
,因此,当您调用this
,它将引用自己的this
而不是外部的this
。
For details, you may take a look on the MDN web docs 有关详细信息,您可以查看MDN网络文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.