3

我有一个任务要做 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 对象。

4

2 回答 2

2

尝试使用

var jsonData = ko.toJSON(this); 

代替

var jsonData = ko.toJSON(ViewModel);
于 2013-01-28T12:46:16.840 回答
1

直接使用这个 --- data: { total_changes: ko.toJSON(this) }。

于 2013-03-14T21:46:44.337 回答