Reputation: 3442
I have such code. The main problem is that var jsonOfLog = JSON.stringify(data);
gives correct JSON "[{"name":"Jhon"},{"name":"Nick"},{"name":"Sanders"}]"
but var jsonOfLog = JSON.stringify(test);
gives undefined
.
Why? It's problem with types or something else? How to fix this?
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());
Upvotes: 0
Views: 91
Reputation: 4443
I see a couple things in your code that could be causing the problem.
First, the test
variable is a reference to self.items
, which is a Knockout observableArray
and not a native JavaScript array. I'm not very familiar with Knockout, but that may not serialize as an array.
Also, on the first line of your constructor function, you are assigning to self
without using var
. This is assigning a value to a global variable instead of a local. If you have a similar construct elsewhere in your code, it is likely that the self
reference is getting overwritten.
Upvotes: 1
Reputation: 672
You can't stringify an observable array like that; you end up stringifying the function and not the array. You should be using the ko.toJSON(viewModel)
function for that.
Remember, in KnockOut, you always need to use the object.myObservableValue()
to access the actual value of the observable (instead of object.myObservableValue
), otherwise you end up using the function instead of the value.
Upvotes: 0