Django Javascript Explanation
I have this code and I'm trying to make sense of it - I'm not really sure how it works-
{% if book %}
<script type='text/javascript'>
$(document).ready(function() {
$.get('/ajax/book/{{ book.id }}/timetable/', {}, function(data) {
data = JSON.parse(data);
var events = new Array();
for (var i in data) {
events.push({
id: data[i].id,
title: '{{ request.user.name }}',
start: Date.parse(data[i].startTime, "yyyy-MM-dd HH:mm:ss"),
end: Date.parse(data[i].endTime, "yyyy-MM-dd HH:mm:ss"),
allDay: false
});
}
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaDay,agendaWeek'
},
theme: true,
contentHeight: 400,
defaultView: 'agendaWeek',
selectable: true,
selectHelper: true,
eventClick: function(calEvent, jsEvent, view) {
},
select: function(start, end, allDay) {
var title = '{{ request.user.name }}';
$.post('/ajax/book/{{ book.id }}/timetable/new/', {
csrfmiddlewaretoken: getCookie('csrftoken'),
startTime: start.format("yyyy-mm-dd HH:MM:ss"),
endTime: end.format("yyyy-mm-dd HH:MM:ss"),
}, function(data) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
});
calendar.fullCalendar('unselect');
},
editable: true,
events: events,
eventResize: function(event, dayDelta, minuteDelta, revertFunc) {
alert(
"The end date of " + event.title + " has been moved " +
dayDelta + " days and " +
minuteDelta + " minutes."
);
if (!confirm("Is this okay?")) {
revertFunc();
}
}
});
});
});
</script>
From what I can tell, ajax/book/.../timetable and ajax/book/.../timetable/new call book_timetable(request,id) and book_timetable_new(request,id)-
url(r'^ajax/book/(?P<bookid>\d+)/timetable/$', twobooks.ajax.views.book_timetable),
url(r'^ajax/book/(?P<bookid>\d+)/timetable/new/$', twobooks.ajax.views.book_timetable_new),
where the functions are -
def book_timetable(request, bookid):
book = get_object_or_404(Book, id=bookid)
rawslots = TimeSlot.objects.filter(user=request.user).filter(book=book)
slots = []
for rawslot in rawslots:
slot = {
'id': rawslot.id,
'startTime': str(rawslot.startTime),
'endTime': str(rawslot.endTime),
}
slots.append(slot)
return HttpResponse(simplejson.dumps(slots))
def book_timetable_new(request, bookid):
book = get_object_or_404(Book, id=bookid)
startTime = datetime.strptime(request.POST['startTime'], "%Y-%m-%d %H:%M:%S")
endTime = datetime.strptime(request.POST['endTime'], "%Y-%m-%d %H:%M:%S")
timeslot = TimeSlot(
user = request.user,
book = book,
开发者_Python百科 startTime = startTime,
endTime = endTime,
)
timeslot.save()
return JSONify("")
I'm trying to do something similar to this, except with other data, which is why I'm trying to get how this works. If anyone could explain it to me it'd be great!
This is a fairly standard AJAX pattern. The template is rendered by the original view, as normal. In the course of rendering, some elements of the Javascript which are marked as Django template variables are filled in - eg {{ book.id }}
and {{ request.user.name }}
- so that by the time it gets to the browser, those are indistinguishable from the rest of the JS.
Now, the Javascript makes a call to the server, passing those elements. The server responds with JSON data, which is parsed by the function which is the third parameter to the .get
call. I haven't looked too deeply into that function, but it seems to be using that data to instantiate a fullCalendar
, which is presumably a separate jQuery script.
One slightly strange thing is that the AJAX call is set to run as soon as the browser has loaded the page - normally there's no point doing that, since you could simply include the data in the original template. Usually AJAX is set to execute in response to some event in the browser, such as a button click.
精彩评论