从变量获取事件

getting the event from variable

我正在研究来自 github 的 jquery 日历:https://github.com/themouette/jquery-week-calendar

我使用 C# 代码从数据库中提取数据,并将其存储在 hiddenfield,然后 javascript 读取 hiddenfield 字段值作为字符串。

我将跳过如何从数据库中获取值,在这个问题中,我将事件硬编码到 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 是字符串而不是数组。

event 正在接受 array 而不是 string

要使用数组试试这个:

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