我试图在django中使用这个eventCalendar:http://jquery-week-calendar.googlecode.com/svn/trunk/jquery.weekcalendar/full_demo/weekcalendar_full_demo.html
我想自己编写ajax代码,但另一方面我是jquery ajax的新手,我想发送事件数据包括startTime,endTime等,以便在日历上显示:
$('#calendar').weekCalendar({
data: function(callback){
$.getJSON("{% url DrHub.views.getEvents %}",
{
},
function(result) {
callback(result);
}
);
}
});
此日历以此格式获取数据:
return {
events : [
{
"id":1,
"start": new Date(year, month, day, 12),
"end": new Date(year, month, day, 13, 30),
"title":"Lunch with Mike"
},
{
"id":2,
"start": new Date(year, month, day, 14),
"end": new Date(year, month, day, 14, 45),
"title":"Dev Meeting"
},
...
]
};
如何在getEvents
视图中格式化数据库中提取的数据?
答案 0 :(得分:1)
from django.utils import simplejson
def some_view(request):
# Build the output -> it's a standard Python dict
output = {
"events": [
{
"id": 1,
"start": "2009-05-10T13:15:00.000+10:00",
"end": "2009-05-10T14:15:00.000+10:00",
"title":"Lunch with Mike"
},
]
}
# With db data you would do something like:
# events = Event.objects.all()
# for event in events:
# event_out = {
# "title": event.title,
# # other fields here
# }
# output['events'].append(event_out)
# Return the output as JSON
return HttpResponse(simplejson.dumps(output), mimetype='application/json')
答案 1 :(得分:0)
您可以像往常一样构建字典,只需考虑日期的字符串不会在没有处理的情况下在javascript中解释。我的建议是直接发送javascript可解释的日期,而不是字符串,如下所示:
from django.utils import simplejson
import datetime
import time
occ.start = time.mktime(occ.start.timetuple())*1000
occ.end = time.mktime(occ.end.timetuple())*1000
event = {'id': occ.id,'title':occ.title,'start':occ.start,'end':occ.end,'body':occ.description,'readOnly': '%r' %occ.read_only,'recurring':'%r' % occ.recurring,'persisted': '%r' % occ.persisted,'event_id':occ.event.id}
mimetype = 'application/json'
return HttpResponse(simplejson.dumps(event),mimetype)
考虑到日历需要'events'键,所以:
$.getJSON(url, function(data){
res = {events:data};
//alert(JSON.stringify(res, null, 4));
callback(res);
});
如果您在javascript端进行处理,请尝试使用可以从文本转换日期的库datejs。