我试图在ajax调用从以下页面返回后显示菜单数据:
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<!-- <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.js'></script> -->
</head>
<body>
<h1>page loaded</h1>
<div data-bind="foreach: menu">
<!-- ko foreach: items -->
<span data-bind="$data.name"></span>
<!-- /ko -->
</div>
</body>
<script>
function OrderPageViewModel() {
var self = this;
// self.menu_loaded_success_callback = function(data) {
// var retrieved_menu = data["menu"];
// self.menu = ko.observable(retrieved_menu);
// console.log(retrieved_menu)
// alert(data);
// }
//
// self.get_data(menu_url).done(self.menu_loaded_success_callback);
}
var menu_url = "menu/get-menu";
get_menu_data = function(url_ending){
console.log("running get_data");
var URL = "/api/&/".replace("&", url_ending);
console.log("URL: ", URL);
return $.ajax({
dataType: "json",
url: URL,
// type: "GET",
});
}
get_menu_data(menu_url).done(function(data){
var vm = new OrderPageViewModel();
console.log(data);
vm = ko.mapping.fromJSON(data);
ko.applyBindings(vm);
}).fail(function(){
alert("failed");
});
// ko.applyBindings(new OrderPageViewModel());
</script>
我按照wait for ajax result to bind knockout model的示例进行操作,它说的是
Uncaught TypeError: Cannot read property 'fromJSON' of undefined
最佳答案
fromJSON
方法是Knockout mapping plugin的一部分,它没有包含在代码Knockout库中。
您必须单独包含映射插件,因此在添加了剔除后添加以下行:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js" type='text/javascript'></script>