2012-02-25 62 views
1

I'me嘗試使用此eventCalendar在Django:http://jquery-week-calendar.googlecode.com/svn/trunk/jquery.weekcalendar/full_demo/weekcalendar_full_demo.html格式的數據阿賈克斯

我想編寫AJAX代碼自己,但在另一方面I'me jQuery的阿賈克斯一個新手,我想發送事件數據包括開始時間,結束時間等,以顯示他們在日曆上:

$('#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" 
     }, 
     ... 
    ] 
    }; 

我如何格式化從DAT獲取的數據在getEvents查看?

回答

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') 
+0

非常感謝@Secator,你的回答非常好,當我要使用數據庫來填寫這個字典時,我得到這個錯誤,「全局名稱」輸出沒有被定義「,我不知道如何定義輸出的循環!我知道我的問題是可笑的,但我不知道我應該尋找什麼來解決這個問題! – 2012-02-26 16:41:58

+0

當我把這之前for循環:輸出= {},它會導致另一個錯誤:「例外類型:KeyError在/醫生/ shahsavand /訪問/ getEvents/ 異常值:'事件'」! – 2012-02-26 17:16:23

+1

嘗試:'output = {「events」:[]}' – 2012-02-26 17:56:53

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) 

考慮到日曆預計「事件」鍵,以便:

$.getJSON(url, function(data){ 
       res = {events:data}; 
       //alert(JSON.stringify(res, null, 4)); 
       callback(res); 
      }); 

如果您在preffer處理javascript方面試試可以從文本轉換日期的庫datejs