从ajax调用填充observableArray

时间:2015-11-20 01:02:18

标签: knockout.js knockout-mapping-plugin

单击“添加”按钮,将获取db的结果。 我希望这个结果可以在observableArray中填充或计算(为将来计算)。

我对如何填充可观察数组毫无头绪。下面是ajax调用的代码

KNOCKOUTJS

self.addToCartViaProdList = function (item, event) 
{
    /*get current item index*/
    /*in dom element $index() is enough but in viewModel a context is to be obtained*/
    var context = ko.contextFor(event.target);
    var index = context.$index();
    var incQty = self.prodList()[index].ProductQty();
    var prodID = self.prodList()[index].ProductID();

    var verProdInCombo = ko.toJS({"prodID":prodID});
    //check product in combos
    $.ajax
    ({
        url: '**************ProdID.php', 
        type: "post",
        data: verProdInCombo,
        success: function(result) 
        {
            /*The result is in below format*/
            /***************
            "{"ComboName":"SinglePack","ComboItemsName":"Aloo Tikki Burger,Mango Lassi,Tomato Soup","ComboItemsID":"101_1_11,1105_11_110,901_9_90","ComboTotalPrice":"90.25"}"
            ********************/
        }, 
        error: function(xhr, status){
            alert(xhr);
            alert(status);
        }
    });
};

我获得了成功的结果,但我将这些数据放入observableArray的所有尝试都没有取得任何丰硕的成果。

我尝试将结果保存在localSession中。然后使用计算变量从该localSession中选择值

然后我尝试使用ko.mapping.fromJS(结果),这不起作用

我想在div中显示从服务器收到的列表,如下所示:

HTML CODE

<div class="comboSeg" >
    <div data-bind="foreach: comboDataList">
        <div data-bind="text: ComboName">
        </div>
        <div data-bind="text: ComboItemsName">
        </div>
        <div data-bind="text: ComboTotalPrice">
        </div>
    </div>
</div>

尝试的不同版本的knockoutjs是:

版本1:在本地会话中保存数据并使用计算

self.comboDataList = ko.computed(function()
{
    var comboDataItems = [];
    if (self.comboValChange() == "DO" && localStorage.getItem("comboDataItem") != null)
    {
        var dataSaved = localStorage.getItem("comboDataItem");
        comboDataItems = ko.utils.arrayMap(dataSaved, function(item)
        {
            return new ComboList(item.ComboName, item.ComboItemsName, item.ComboItemsID, item.ComboTotalPrice);
        });

        comboDataItems.push(dataSaved);
    }

    return comboDataItems;
},this);

//Ajax call is as follows:

    $.ajax
    ({
        url: '***************ProdID.php', 
        type: "post",
        data: verProdInCombo,
        success: function(result) 
        {
            localStorage.removeItem("comboDataItem");
            localStorage.setItem("comboDataItem",result);
            //Forcing the computed function to be called, just a workaround
            self.comboValChange("");
            self.comboValChange("DO");
        }, //Result will contain whatever server will send back as a mesage
        error: function(xhr, status){
            alert(xhr);
            alert(status);
        }
    });

版本2:推动在comboDataList

中收到的成功消息
    $.ajax
    ({
        url: '*************ProdID.php', 
        type: "post",
        data: verProdInCombo,
        success: function(result)
        {
            self.comboDataList.push(result);
            //Also tried below one
            //self.comboDataList.push(ko.toJS(result));
        }, //Result will contain whatever server will send back as a mesage
        error: function(xhr, status){
            alert(xhr);
            alert(status);
        }
    });

现在我在浏览器中启用了denug我得到了这两个版本的错误消息:

错误:未捕获的ReferenceError:无法处理绑定“text:function(){return ComboName}” 消息:未定义ComboName

2 个答案:

答案 0 :(得分:1)

只需将中的observableArray作为Ajax调用的成功函数插入:

$.ajax
({
    url: '**************ProdID.php', 
    type: "post",
    data: verProdInCombo,
    success: self.comboDataList, 
    error: function(xhr, status){
        alert(xhr);
        alert(status);
    }
});

假设您不需要更新数组行内的各个元素。

答案 1 :(得分:0)

这就是我工作的方式,猜猜这不是最好的方法。 简单地将成功的JSON对象推送到observableArray并没有反映在我的html页面中,因此我使用了计算来完成它。

KNOCKOUT代码

self.comboDataList = ko.computed(function()
{
    var comboDataItems = [];
    //self.comboValChange() an observable variable just to invoke the computed function everytime there is update
    if (self.comboValChange() == "DO" && localStorage.getItem("comboItems") != null)
    {
        var dataSaved = ko.utils.parseJson(localStorage.getItem("comboItems"));
        comboDataItems = ko.utils.arrayMap(dataSaved, function(item)
        {
            return new ComboList(item.ComboName, item.ComboItemsName, item.ComboItemsID, item.ComboTotalPrice);
        });

        comboDataItems.push(dataSaved);
    }

    return comboDataItems;
},this);


//The ajax call
    $.ajax
    ({
        url: '**************ProdID.php', 
        type: "post",
        data: verProdInCombo,
        dataType:'json',
        success: function(result) 
        {
            //using localStorage to store the result
            localStorage.removeItem("comboItems");
            localStorage.setItem("comboItems", ko.toJSON(result));
            //updating so that everytime computed is called
            self.comboValChange("");
            self.comboValChange("DO");
        }, //Result will contain whatever server will send back as a mesage
        error: function(xhr, status){
            alert(xhr);
            alert(status);
        }
    });

HTML是:

    <div class="comboSeg" >
        <div data-bind="foreach: comboDataList">
            <div data-bind="text: ComboName">
            </div>
            <div data-bind="text: ComboItemsName">
            </div>
            <div data-bind="text: ComboTotalPrice">
            </div>
        </div>
    </div>

JSON的结构是:

"{"ComboName":"SinglePack","ComboItemsName":"Aloo Tikki Burger,Mango Lassi,Tomato Soup","ComboItemsID":"101_1_11,1105_11_110,901_9_90","ComboTotalPrice":"90.25"}"‌

因此视图模型将是:

function ComboList(ComboName, ComboItemsName, ComboItemsID, ComboTotalPrice)
{
    this.ComboName = ko.observable(ComboName);
    this.ComboItemsName = ko.observable(ComboItemsName);
    this.ComboItemsID = ko.observable(ComboItemsID);
    this.ComboTotalPrice = ko.observable(ComboTotalPrice);
}