如何使用cookie数组中的项填充KO绑定列表

时间:2016-02-17 15:09:12

标签: javascript json cookies knockout.js

我正在构建一个cookie来临时保存购物车项目并尝试使用我的cookie中的数组字符串填充一个淘汰列表。

但KO似乎并不了解cookie中的数组是一个数组,也不会遍历表中的数组。

当用户点击"添加到购物车"按钮会发生这种情况:

["can't"]

推入数组的两个项目的示例:

[[{" datetime":" 2016-02-17 14:31:34"," id":" 749" " typeid的":" 13""数量":1}],[{"日期时间":" 2016-02 -17 14:59:26"," id":" 756"," typeid":" 13",&#34 ;数量":1}]]

所以现在我想让一个表自动填充这些项的日期时间。所以我的ko看起来像这样:

$("#add2cart").click(function() {
function complete() {

//Animation saying added to cart
    $("<div>").text("Added to cart!").appendTo("#log");
    $("#log").show("fast");

  //formats date for db
    var datetime = new Date().toISOString().slice(0, 19).replace("T", " ");

  //gathers cookie data
 var itemsString = $.cookie("cookieCart");
    var items = "";

    if (itemsString === "undefined") {
        itemsString = "";
    } else {
        if (itemsString != null) {
            //parses the cookie array
            items = JSON.parse(itemsString); // unserialize
        } else {
            items = [];
        }
        //UPDATE *I REMOVED THE BRACKETS BECAUSE IT WAS MAKING AN ARRAY OF AN ARRAY*
     var newItem = { datetime: datetime, id: id, typeid: typeid, qty: 1       };
        items.push(newItem); // modify
        $.cookie("cookieCart", JSON.stringify(items), { path: "/" });  //   serialize
    }
}

$("#add2cart").fadeOut(1000, "linear", complete);
});

我的表格如下:

var itemArray = [];
var cartItems = $.cookie("cookieCart");
itemArray = JSON.parse(cartItems); // unserialize

ko.applyBindings({
cartItemArray: cartItems
});

当我运行它时,javascript崩溃

未捕获的ReferenceError:无法处理绑定&#34; foreach:function(){return cartItemArray}&#34; 消息:无法处理绑定&#34; text:function(){return datetime}&#34; 消息:未定义日期时间

当我更改data-bind =&#34; text:datetime&#34; to data-bind =&#34; text:cartItems&#34;

它给了我:

[[{&#34; datetime&#34;:&#34; 2016-02-17 14:31:34&#34;,&#34; id&#34;:&#34; 749&#34; &#34; typeid的&#34;:&#34; 13&#34;&#34;数量&#34;:1}],[{&#34;日期时间&#34;:&#34; 2016-02 -17 14:59:26&#34;,&#34; id&#34;:&#34; 756&#34;,&#34; typeid&#34;:&#34; 13&#34;,&#34 ;数量&#34;:1}]] [[{&#34; datetime&#34;:&#34; 2016-02-17 14:31:34&#34;,&#34; id&#34;:&#34; 749&#34;,&# 34; typeid&#34;:&#34; 13&#34;,&#34; qty&#34;:1}],[{&#34; datetime&#34;:&#34; 2016-02-17 14 :59:26&#34;&#34; ID&#34;:&#34; 756&#34;&#34; typeid的&#34;:&#34; 13&#34;&#34;数量&# 34;:1}]] [[{&#34; datetime&#34;:&#34; 2016-02-17 14:31:34&#34;,&#34; id&#34;:&#34; 749&#34;,&# 34; typeid的&#34;:&#34; 13&#34;&#34;数量&#34;:1}], ...

(好几次)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

所以答案很简单,因为我在推送到阵列的项目上有额外的括号:

 var newItem = [{ datetime: datetime, id: id, typeid: typeid, qty: 1}];

需要

 var newItem = {datetime: datetime, id: id, typeid: typeid, qty: 1};