【发布时间】:2016-06-04 06:56:01
【问题描述】:
我有这样的代码。主要问题是 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());
【问题讨论】:
-
console.log(self.items) 输出什么?
-
你的
AppViewModel函数不应该有return吗? -
@Quantastical 构造函数需要返回值做什么?
-
@Tomalak 我以为他们刚刚调用了
AppViewModel()并将返回值传递给ko.applyBindings参数。
标签: javascript json knockout.js