我在 asp.net mvc 页面上使用 knockoutjs。我正在使用 ajax 通过调用 ko.toJSON(viewModel)
将表单保存回服务器。然后使用 jQuery 将结果发布回服务器。 View 模型上的所有属性都已成功序列化,但 Javascript 日期除外,该日期作为空对象持久化。
声明:
var viewModel = {
startTime: ko.observable(),
type: ko.observable(),
durationInMinutes: ko.observable(),
notes: ko.observable()
};
保存数据:
var postData = ko.toJSON(viewModel);
$.ajax({
url: "/data",
type: "POST",
data: postData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log('success!');
},
error: function () {
console.log('fail!');
}
});
viewModel.startTime() 的 console.log 值为:
Date {Tue May 10 2011 11:30:00 GMT-0500 (Central Daylight Time)}
第 1 行之后保存数据 ,postData 的值为:
{
"startTime": {},
"type": "1",
"durationInMinutes": "45",
"notes": "asfasdfasdfasdfasdfasdfasdfas",
"displayableStartTime": "10-May 11:30"
}
如果我扩展 的第 1 行保存数据 到
var jsonEvent = ko.toJS(viewModel);
jsonEvent.startTime = viewModel.startTime();
var postData = JSON.stringify(jsonEvent);
postData 的值为:
{
"startTime": "2011-05-10T16:30:00.000Z",
"type": "1",
"durationInMinutes": "45",
"notes": "asfasdfasdfasdfasdfasdfasdfas",
"displayableStartTime": "10-May 11:30"
}
谁能解释可能发生的事情以及我如何能够让 knockoutjs 处理日期对象?
最佳答案
鉴于 ko.toJS 和日期的当前问题,一种选择是创建一个dependentObservable,其中包含您希望服务器处理的实际值。
就像是:
var viewModel = {
startTimeForInput: ko.observable(),
type: ko.observable(),
durationInMinutes: ko.observable(),
notes: ko.observable()
};
viewModel.startTime = ko.dependentObservable(function() {
return this.startTimeForInput().toJSON();
}, viewModel);
ko.applyBindings(viewModel);
现在,当您调用
ko.toJSON
你会得到startTime
具有服务器可以使用的正确值。对于较旧的浏览器,类似于 json2.js将包括 Date 对象的 .toJSON。
关于ajax - ko.toJSON() 是否适用于日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942789/