JavaScript OOP-无法在类结构内通过Ajax调用设置公共值
我在编写一个专门处理Ajax调用及其响应的类时遇到了这个问题 下面代码的用途:根据数据库中存在的用户记录,我需要设置“isPersonalDivRequiredFlag”标志以供进一步使用JavaScript OOP-无法在类结构内通过Ajax调用设置公共值,javascript,ajax,class,Javascript,Ajax,Class,我在编写一个专门处理Ajax调用及其响应的类时遇到了这个问题 下面代码的用途:根据数据库中存在的用户记录,我需要设置“isPersonalDivRequiredFlag”标志以供进一步使用 // New ajax request class function ajaxRequestHandler(){ this.needOutPutInJSON = 0; this.url = "/libraries/ajaxHelper.php"; this.requestTyp
// New ajax request class
function ajaxRequestHandler(){
this.needOutPutInJSON = 0;
this.url = "/libraries/ajaxHelper.php";
this.requestType = "POST";
this.isPersonalDivRequiredFlag = 0;
};
// Methods written for Class ajaxRequestHandler
ajaxRequestHandler.prototype = {
sentRequest : function(userData, typeID){
var options = {type: this.requestType, context: this, url: this.url, data: { data: userData, type: typeID }};
if(this.needOutPutInJSON){
options.dataType = "json";
}
// Check whether user want to see the response
options.success = function(rec){
if(rec == "1"){
this.isPersonalDivRequiredFlag = 1;
}
};
//Jquery Ajax
$.ajax(options);
},
enableJSONoutput : function(){
this.needOutPutInJSON = 1;
},
getFlagValue : function(){
return this.isPersonalDivRequiredFlag;
},
setFlagValue : function(){
console.log('Setflag Func called.');
this.isPersonalDivRequiredFlag = 1;
}
};
我使用下面的代码
var newRequest = new ajaxRequestHandler();
console.log('Before change [Value of isPersonalDivRequiredFlag variable] : ' + newRequest.getFlagValue()); // Output 0
newRequest.sentRequest({}, "recordExist");
console.log('After change [Value of isPersonalDivRequiredFlag variable] : ' + newRequest.getFlagValue()); // Output 0
当我在Ajax调用的Success方法中将标志“isPersonalDivRequiredFlag”设置为1时,它无法保留这个值,因为它将通过自己的方法“getFlagValue”函数访问它
如果我删除Ajax调用函数并使其成为一个普通的原型方法,那么整个代码都可以正常工作。因此,我知道原因,但无法找到任何解决方案:(
我已经试过什么了?
我在网上搜索时发现了一些人们建议的技术。
a) 在Ajax调用中使用了此配置,但运气不佳:( b) 内部成功方法:
var myclass = this;
并调用原型函数,如下所示
myclass.setFlagValue();
但是没有运气:(您解决问题的方法是正确的(任何一种)。但是另一个问题是,在您尝试读取新值的那一刻,还没有收到Ajax响应,因此您仍然得到旧值。Ajax是异步的。您将代码放在
ewRequest.sentRequest({},“recordExist”)之后;
在收到响应和调用成功回调之前立即运行。看看这个问题:感谢@felix kling推荐了这么好的一篇文章。我计划使用回调
myclass.setFlagValue();