如何使用json对象使用knockout.js将值保存到数据库

时间:2013-01-28 12:26:13

标签: ruby json knockout.js ruby-on-rails-3.2

我有一个任务要做knockout.js。在这里,我有一个模范员工,其中包含字段名称,国家和州。在编辑这个时我想保存它。但是当我这样做时我无法保存它。 我的编辑页面是

<%= javascript_include_tag "knockout-2.2.0" %>
<script>
$(document).ready(function() {


    // Here's my data model
        var ViewModel = function(){
            this.country = ko.observable();
            this.state = ko.observable();
            this.name = ko.observable();
            this.fullName = ko.computed(function() {
                return this.country() + " " + this.state();
                 }, this);

            this.save = function(){

                var jsonData = ko.toJSON(ViewModel);
                alert("Could now send this to server: " + JSON.stringify(jsonData));

                $.ajax({
                    url: '/employees/<%=@employee.id%>',
                    dataType: 'json',
                    type: 'PUT',
                    data: { total_changes: JSON.stringify(jsonData) },

                    success: function(data){
                        alert("Successful");
                    },
                    failure: function(){
                        alert("Unsuccessful");
                    }
                });
            }
};


        ko.applyBindings(new ViewModel());

});
</script>


<%= form_for(@employee) do |f| %>
  <% if @employee.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@employee.errors.count, "error") %> prohibited this employee from being saved:</h2>

      <ul>
      <% @employee.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <input data-bind='value: name, valueUpdate: "afterkeydown"' />
  </div>
 <div class='label'>
        <%= f.label :country %><br />
        <input data-bind='value: country, valueUpdate: "afterkeydown"' />
  </div>
  <div class="field">
    <%= f.label :state %><br />
    <input data-bind='value: state, valueUpdate: "afterkeydown"' />
  </div>

<p>Name:
<span data-bind="text: name"> </span></p>

<p>Country:
<span data-bind="text: country"> </span></p>

<p>State:
<span data-bind="text: state"> </span></p>
 <button data-bind='click: save'>Submit</button>
  </div>
<% end %>

我无法获取json对象。

2 个答案:

答案 0 :(得分:2)

尝试使用

var jsonData = ko.toJSON(this); 

而不是

var jsonData = ko.toJSON(ViewModel);

答案 1 :(得分:1)

直接使用---数据:{total_changes:ko.toJSON(this)}。