knockout.js将表单保存到json [英] knockout.js save form to json

查看:117
本文介绍了knockout.js将表单保存到json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用knockout.js和映射插件映射我的表单。我准备将表单保存到json并将其发送回服务器。这是我第一次这样做,这是最简单的方法吗?

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>


推荐答案

要将viewmodel序列化回JSON,请使用 ko.toJSON(myViewModel)

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

我还建议您阅读发布

编辑:
我可能误解了你想要的东西,但如果你想通过viewmodel提交你可以做这个:

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);
    });

这篇关于knockout.js将表单保存到json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆