3

我因为这段代码而感到沮丧:

    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 come via Ajax.})但myDiv包含undefined. 这告诉我setRes()正确调用了,但它只是没有设置 res 的值。

我不知道为什么。

4

1 回答 1

3

考虑 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;
});
于 2012-10-26T09:13:16.577 回答