我有这样的代码。主要问题是var jsonOfLog = JSON.stringify(data);提供正确的JSON "[{"name":"Jhon"},{"name":"Nick"},{"name":"Sanders"}]",但是var jsonOfLog = JSON.stringify(test);提供undefined

为什么?类型或其他问题吗?如何解决这个问题?

function AppViewModel() {

    self = this;
    self.items = ko.observableArray();
    self.addItems = function () {
        self.items.push({ Name: 'Test', Date: 'Test', Time: 'Test'});
    }
    function time_format(d) {
        hours = format_two_digits(d.getHours());
        minutes = format_two_digits(d.getMinutes());
        seconds = format_two_digits(d.getSeconds());
        return hours + ":" + minutes + ":" + seconds;
    }
    function format_two_digits(n) {
        return n < 10 ? '0' + n : n;
    }
    self.save = function () {
        data = [{ name: 'Jhon' }, { name: 'Nick' }, { name: 'Sanders' }];
        var test = self.items;
        var jsonOfLog = JSON.stringify(test);

        debugger;
        $.ajax({
            type: 'POST',
            dataType: 'text',
            url: "ConvertLogInfoToXml",
            data: "jsonOfLog=" + jsonOfLog,
            success: function (returnPayload) {
                console && console.log("request succeeded");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console && console.log("request failed");
            },

            processData: false,
            async: false
        });
    }
    self.capitalizeLastName = function () {
        debugger;

        var date = $("#date").val();


        $.ajax({
            cache: false,

            type: "GET",

            url: "GetByDate",

            data: { "date": date },

            success: function (data) {

                var result = "";

                $.each(data, function (id, item) {
                    var tempDate = new Date();
                    var tempTime = item.Time;
                    debugger;
                    tempDate =new Date(parseInt(item.Date.replace("/Date(", "").replace(")/", ""), 10));
                    self.items.push({ Name: item.Name, Date: (tempDate.getMonth() + 1) + '/' + tempDate .getDate() + '/' + tempDate.getFullYear(), Time: tempTime.Hours });
                });
            },

            error: function (response) {
                debugger;
                alert('eror');
            }
        });

    }
}

ko.applyBindings(new AppViewModel());

最佳答案

我在您的代码中看到了几处可能导致问题的原因。

首先,test变量是对self.items的引用,这是一个淘汰赛observableArray,而不是本机JavaScript数组。我对淘汰赛不是很熟悉,但是可能无法序列化为数组。

同样,在构造函数的第一行,您正在分配给self而不使用var。这是为全局变量而不是局部变量赋值。如果您在代码的其他位置具有类似的构造,则self引用可能会被覆盖。

07-24 09:50
查看更多