从变量获取事件

时间:2015-04-27 07:00:40

标签: javascript jquery calendar

我正在从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 '

谁能告诉我,我错过了什么?

1 个答案:

答案 0 :(得分:1)

因为您创建的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);