我有一个json文件,我通过api加载。 json文件将是一个商店数组。当我加载页面时,这是我在stacktrace中得到的错误:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return stores }"
Message: stores is not defined
这是从API返回的json看起来像:
[
{
"store_name": "Aber",
"store_wiki_folder": "#F",
"store_wiki_contact": "#C",
"store_wiki_access": "#A",
"store_db": "db:127.2.3.1:9000",
"sites": [
{
"label": "Prod",
"link": "http://google.com",
"special_label": "[Admin]",
"special_link": "http://images.google.com"
},
{
"label": "Train",
"link": "http://google.com",
"special_label": "[Admin]",
"special_link": "http://images.google.com"
}
]
},
{
"store_name": "Academy",
"store_wiki_folder": "#F",
"store_wiki_contact": "#C",
"store_wiki_access": "#A",
"store_db": "db:127.2.3.1:9000",
"sites": [
{
"label": "Live",
"link": "http://google.com",
"special_label": "[Admin]",
"special_link": "http://images.google.com"
},
{
"label": "Test",
"link": "http://google.com",
"special_label": "[Admin]",
"special_link": "http://images.google.com"
}
]
}
]
这是我必须从api中提取并执行ko绑定:
$.getJSON("/api/stores", function(stores) {
var storesModel = ko.mapping.fromJSON(stores);
ko.applyBindings(storesModel);
})
我正在使用Jade来构建我的布局:
extends layout
block content
.container(role="main")
.row
.col-md-12
ul(data-bind="foreach:stores")
li(data-bind="text: store_name")
我认为这可能与我构建json文件的方式有关。可以更改json文件的结构。
答案 0 :(得分:2)
"foreach:stores"
假设您在模型中有stores
属性。
你展示的只是一个没有它的数组,所以你需要这样的东西:
ko.applyBindings({ stores: storesModel });