问题描述:

i have to get a value from my REST service and assign it to knockout observable

the code looks like

 mydata=$.ajax({ url: 'http://myserver:7101/MUDRESTService/rest/v1/mudstats?onlyData=true',

type: 'get',

dataType: 'json',

success: function(output) {

dailyMinRest = JSON.parse(mydata.responseText).items[0].AvgSession;

console.log(dailyMinRest)

sessionCountRest = JSON.parse(mydata.responseText).items[0].Sessions;

}

});

self.dailyMin = ko.observable(dailyMinRest);

the problem is with the last line. if i keep here the obviously there is no guranteed for it to execute after rest returns the response. however, if i move it to inside the succss method then the self variable is not resolved.

网友答案:

Create the dailyMin observable immediately and then update it when your ajax request completes by calling the observable and passing in the new value:

self.dailyMin = ko.observable();
mydata=$.ajax({
    url: 'http://myserver:7101/MUDRESTService/rest/v1/mudstats?onlyData=true',
    type: 'get',  
    dataType: 'json',    
    success: function(output) {
        self.dailyMin(JSON.parse(mydata.responseText).items[0].AvgSession);
    }
});

BTW, I'm not sure why you're calling JSON.parse(mydata.responseText) instead of using the already parsed JSON response in output, but I'll assume you know what you're doing there :-).

相关阅读:
Top