knockout.js save form to json

ぐ巨炮叔叔 提交于 2019-12-11 03:43:43

问题


I have my form mapped using knockout.js and mapping plugin. I am ready to save the form to json and send it back to the server. This is my first time doing this so what is the simplest way to do it?

Here is what I have so far:

// Here's my data model
var viewModel;
$.getJSON('/myJSONdata', function (data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

//convert mapped data to json format
var jsonData = ko.mapping.toJSON(viewModel);

// Do something to send the form data in json format back to the server on form submit

<form data-bind="submit: doSomething">
  <label for="typeOfIncident">Do you agree?</label>
  <label>
  <input type="radio" name="doYouAgree" value="Yes" data-bind="value: doYouAgree" checked>
  Yes
  </label>
  <label>
  <input type="radio" name="doYouAgree" value="No" data-bind="value: doYouAgree">
  No
  </label>

  <!-- submit button -->
  <button type="submit">Submit</button>
</form>

回答1:


To serialize your viewmodel back to JSON use ko.toJSON(myViewModel)

I would also recommend reading this post.

Edit: I may be misunderstanding what you are wanting here, but if you wanted to submit through the viewmodel you could do this:

   var viewModel;
   $.getJSON('/myJSONdata', function (data) {
      viewModel = ko.mapping.fromJS(data);
      viewModel.doSomething = function(){
        var jsonData = ko.mapping.toJSON(viewModel);   
        $.ajax({
           type: "POST",
           url: '/myJSONdata',
           data: jsonData
        });
      };
      ko.applyBindings(viewModel);
    });


来源:https://stackoverflow.com/questions/16449387/knockout-js-save-form-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!