来自AJAX调用的淘汰数据不会绑定

时间:2015-03-24 17:06:03

标签: javascript ajax knockout.js

我是淘汰赛的新手,并试图找出以下不起作用的原因。由于某种原因,我从ajax调用返回的数据没有被转换为数组。

我有一个返回一些JSON的函数

bankingApi.client = (function () {

var getSafeFloatCash= function getSafeFloatCash() {
    return $.ajax({
        url: '/BackOffice/Banking/Banking/GetSafeFloat',
        type: 'GET'        
    });
}
    return {
        getSafeFloatCash : getSafeFloatCash
    };
})();

该函数返回以下JSON:

[{"Denomination":"1p","Value":34.1200},{"Denomination":"2p","Value":98.0400},{"Denomination":"5p","Value":85.0500},{"Denomination":"10p","Value":571.2000},{"Denomination":"20p","Value":62.8000},{"Denomination":"50p","Value":57.5000},{"Denomination":"£1","Value":441.0000},{"Denomination":"£2","Value":398.0000},{"Denomination":"£5","Value":260.0000},{"Denomination":"£10","Value":320.0000},{"Denomination":"£20","Value":780.0000},{"Denomination":"£50","Value":350.0000}]

我设置了我的可观察数组

(function () {

var BankingViewModel = function () {
    var self = this;
    self.safeFloatDenominations = ko.observableArray();

    var safeFloatCash = bankingApi.client.getSafeFloatCash();
    self.safeFloatDenominations(safeFloatCash); // does not work!

    self.safeTopUpValue = ko.computed(function () {
        var total = self.floatRecommendedValue - self.safeFloatTotal;
        return total.toFixed(0);
    });        
}

$(document).ready(function () {
    var viewModel = new BankingViewModel();        
        ko.applyBindings(viewModel);        
});

})();

如果我将从ajax调用返回的值粘贴到数组变量中,它可以正常工作,因此将函数调用转换为数组存在一些问题。

这是视图

  <div class="row" data-bind="visible: safeTopUpValue()>0, foreach:     safeFloatDenominations">
<div class="col-xs-5">
    <input type="text" data-bind="value: Value" />
    <label data-bind="text: Denomination"></label>
</div>

1 个答案:

答案 0 :(得分:1)

根据我的评论,$.ajax不会返回数据 - 它会返回承诺。您需要使用它来实际获取数据:

var safeFloatCash = bankingApi.client.getSafeFloatCash();
safeFloatCash.done(function(d) {
    //may need to parse the data:
    //d = JSON.parse(d);
    self.safeFloatDenominations(d);
});