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