我因为这段代码而感到沮丧:
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;
};
}
现在,一旦模型的实例被初始化并且方法被调用如下:
var _model = new Model();
document.getElementById("myDiv").innerHTML = _model.GetAjaxData();
警报弹出并显示预期数据(Ajax 服务仅返回 {Result: this came via Ajax.})但 myDiv
包含 undefined
。这告诉我 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;
});
关于javascript - 尽管使用有效参数调用,但设置方法未设置成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083977/