Javascript 设置方法不使用';虽然使用有效参数调用,但无法设置成员
我因为这段代码而感到沮丧:Javascript 设置方法不使用';虽然使用有效参数调用,但无法设置成员,javascript,oop,Javascript,Oop,我因为这段代码而感到沮丧: function Model(){ this.GetAjaxData = function(){ //private Member to be returned var res; function setRes(newVal){ res = newVal; alert(newVal); // to verify its really
function Model(){
this.GetAjaxData = function(){
//private Member to be returned
var res;
function setRes(newVal){
res = newVal;
alert(newVal); // to verify its really being called
}
// calls a Ajax-Service(1st param) with the given arguments(2nd param),
// the 3rd param is a function with gets called back, commiting the
// output of the Ajax-Service as arguments for the called function
tw.coach.callService(
"GetServerTime",
"<inputs><variable name='input1' type='String'>lala</variable></inputs>",
function(arg){ setRes(arg['Result']); }
);
return res;
};
}
该警报会弹出预期的数据(Ajax服务只返回{Result:这是通过Ajax实现的。}),但myDiv
constainsundefined
。这说明调用了setRes()
,但是没有设置res的值
我也不知道为什么。考虑到AJAX请求的异步性质,更改您的方法:
function Model() {
this.GetAjaxData = function(callback) {
var data = "<inputs><variable name='input1' type='String'>lala</variable></inputs>";
tw.coach.callService("GetServerTime", data, function(arg) {
callback(arg['Result']);
});
};
}
var _model = new Model();
_model.GetAjaxData(function(res) {
document.getElementById("myDiv").innerHTML = res;
});
函数模型(){
this.GetAjaxData=函数(回调){
var data=“lala”;
callService(“GetServerTime”、数据、函数(arg){
回调(arg['Result']);
});
};
}
var_model=新模型();
_model.GetAjaxData(函数(res){
document.getElementById(“myDiv”).innerHTML=res;
});
好的,谢谢您的快速回复!但是有没有办法让函数实际上只返回数据呢?就像等待Ajax任务完成一样?是的,Ajax请求可以是同步的。但是,不推荐它,因为它会阻止UI和其他代码的执行。但这是可能的。检查callService
实现,它应该提供这种可能性,例如设置async:false
。
function Model() {
this.GetAjaxData = function(callback) {
var data = "<inputs><variable name='input1' type='String'>lala</variable></inputs>";
tw.coach.callService("GetServerTime", data, function(arg) {
callback(arg['Result']);
});
};
}
var _model = new Model();
_model.GetAjaxData(function(res) {
document.getElementById("myDiv").innerHTML = res;
});