2017-02-12 38 views
0

我想從以下頁面的AJAX調用返回後顯示的菜單數據屬性「fromJSON」:遺漏的類型錯誤:無法讀取的不確定

<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> 

enter image description here

我跟着的例子在wait for ajax result to bind knockout model和它說Uncaught TypeError: Cannot read property 'fromJSON' of undefined

回答

3

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> 
相關問題