我正在从 github 研究 jquery 日历:https://github.com/themouette/jquery-week-calendar
我使用 C# 背后的代码从数据库中提取数据,并将其存储在隐藏字段中,然后 javascript 将隐藏字段字段值作为字符串读取。
我将跳过如何从数据库获取值,在这个问题中,我将事件硬编码到sampleEvents var中。
工作 JavaScript:
var eventData = {
events: [
{'id':1, 'start': new Date(2015, 3, 27, 12), 'end': new Date(2015, 3, 27, 13, 35),'title':'Lunch with Mike'},
{'id':2, 'start': new Date(2015, 3, 28, 10), 'end': new Date(2015, 3, 28, 14, 45),'title':'Dev Meeting'}
]};
JavaScript 不工作:
var sampleEvents = "{'id':1, 'start': new Date(2015, 3, 27, 12), 'end': new Date(2015, 3, 27, 13, 35),'title':'Lunch with Mike'},{'id':2, 'start': new Date(2015, 3, 28, 10), 'end': new Date(2015, 3, 28, 14, 45),'title':'Dev Meeting'}";
var eventData = {
events: [
sampleEvents
]};
错误消息:
Uncaught TypeError: Cannot read property 'getTime' of undefined
Javascript 2 不工作:
var sampleEvents = "[{'id': 1,'start': new Date(2015, 3, 27, 12),'end': new Date(2015, 3, 27, 13, 35),'title': 'Lunch with Mike'},{'id': 2,'start': new Date(2015, 3, 28, 10),'end': new Date(2015, 3, 28, 14, 45),'title': 'Dev Meeting'}]";
var array = JSON.parse(sampleEvents);
var eventData = {
events:
sampleEvents
};
错误消息:
Uncaught SyntaxError: Unexpected token '
谁能告诉我,我错过了什么?
最佳答案
因为您创建的 sampleEvents
是字符串而不是数组。
事件
接受数组
而不是字符串
。
要使用数组,请尝试以下操作:
var sampleEvents = [
{
'id':1,
'start': new Date(2015, 3, 27, 12),
'end': new Date(2015, 3, 27, 13, 35),
'title':'Lunch with Mike'
},
{
'id':2,
'start': new Date(2015, 3, 28, 10),
'end': new Date(2015, 3, 28, 14, 45),
'title':'Dev Meeting'
}
];
要使用字符串,请尝试以下操作:
var sampleEvents = '['+
'{"id":1, "start": "'+new Date(2015, 3, 27, 12)+'", "end": "'+new Date(2015, 3, 27, 13, 35)+'","title":"Lunch with Mike"},'+
'{"id":2, "start": "'+new Date(2015, 3, 28, 10)+'", "end": "'+new Date(2015, 3, 28, 14, 45)+'","title":"Dev Meeting"}'+
']';
var sampleEventsArray = JSON.parse(sampleEvents);
关于javascript - 从变量获取事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29889177/