3

im getting frustrated because of this piece of code:

    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;
       };
    }

Now, what happens is, once an instance of model has been initialized and the method is being called like:

    var _model = new Model();
    document.getElementById("myDiv").innerHTML = _model.GetAjaxData();

the alert pops up with the expected data (the Ajax Service simply returns {Result: this came via Ajax.}) but myDiv constains undefined. This tells me that the setRes() is called correctly but it just doesn't set the value of res.

And I have no idea why.

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 に答える