我有一个任务要做knockout.js.But我不能将文本框值创建为json对象。 我有一个模型学生,有字段名称和年龄。为了创建新学生我不能将值设置为json对象。 newlist.html.erb
<script>
$(document).ready(function() {
var viewModel = {
firstName: ko.observable(),
_age: ko.observable(),
validationMessage: ko.observable()
};
var self = this;
self.save = function() {
var dataToSave =firstName: ko.observable();
_age: ko.observable();
alert("Could now send this to server: " + JSON.stringify(viewModel));
}
viewModel.Age = ko.dependentObservable({
read: viewModel._age,
write: function (value) {
if (!isNaN(value)) {
this._age(value);
this.validationMessage("");
}
else {
this.validationMessage("Age must be a number!");
}
},
owner: viewModel
});
ko.applyBindings(viewModel);
});
</script>
<h1>Testing</h1>
Name: <input type="text" data-bind="
value: firstName,
valueUpdate : 'afterkeydown'
"/>
<br />
Age: <input type="text" data-bind="value: Age, valueUpdate : 'afterkeydown'" />
<Br />
<span data-bind="text: validationMessage" style="color:Red"></span>
<Br />
<button data-bind='click: save'>Submit</button>
<Br />
但它显示出一些错误。如何创建json对象?
答案 0 :(得分:1)
您可以通过下一种方式将模型转换为json
var dataToSave = {
firstName: viewModel.firstName(),
_age: viewModel._age()
}
此处您的任务已解决:Solution