weixin_33711641 2011-05-09 21:38 采纳率: 0%
浏览 54

ko.toJSON()是否可用于日期?

I am using knockoutjs on an asp.net mvc page. I am using ajax to persist a form back to the server by calling ko.toJSON(viewModel) and then posting the results back to the server using jQuery. All of the properties on the view model are successfully serialized except for the Javascript date which is persisted as an empty object.

Declaration:

var viewModel = {
    startTime: ko.observable(),
    type: ko.observable(),
    durationInMinutes: ko.observable(),
    notes: ko.observable()
};

Save Data:

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

The console.log value of viewModel.startTime() is:

Date {Tue May 10 2011 11:30:00 GMT-0500 (Central Daylight Time)}

After line 1 of Save Data, the value of postData is:

{
    "startTime": {},
    "type": "1",
    "durationInMinutes": "45",
    "notes": "asfasdfasdfasdfasdfasdfasdfas",
    "displayableStartTime": "10-May 11:30"
}

If I expand line 1 of Save Data to

var jsonEvent = ko.toJS(viewModel);
jsonEvent.startTime = viewModel.startTime();
var postData = JSON.stringify(jsonEvent);

The value of postData is:

{
    "startTime": "2011-05-10T16:30:00.000Z",
    "type": "1",
    "durationInMinutes": "45",
    "notes": "asfasdfasdfasdfasdfasdfasdfas",
    "displayableStartTime": "10-May 11:30"
}

Can anyone explain what might be going on and how I might be able to get knockoutjs to handle the date object?

  • 写回答

2条回答 默认 最新

  • weixin_33743703 2011-05-11 16:45
    关注

    Given the current issue with ko.toJS and dates, one option would be to create a dependentObservable containing the real value that you want the server to deal with.

    Something like:

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

    Now, when you call ko.toJSON you will get the startTime with the correct value that the server could use.

    For older browsers, something like json2.js would include the .toJSON for Date objects.

    评论

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示