If you want to pass the URL as a variable to your function, you can do so like this:
<script>
function initializeDataTable(data_url) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : data_url
});
}
$(function(){
initializeDataTable("{% url 'get_menu_list' item.id %}");
});
</script>
Another option is to use tokens in your URL:
<script>
var url_pattern = "{% url 'get_menu_list' '{id}' %}";
function initializeDataTable(id) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : url_pattern.replace('{id}', id)
});
}
$(function(){
initializeDataTable(42);
});
</script>
It's important to note that your token should match the regex type in order to resolve successfully (for example, don't use {id}
if it's defined with \d+
, instead use 0000
).
If you're not entirely satisfied with these solutions, there's an application called django.js that I developed to handle JavaScript within Django projects. You can find more information about it here: django.js.
With django.js, you can simplify your JavaScript code like this:
{% load js %}
{% django_js %}
<script>
function initializeDataTable(id) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : Django.url('get_menu_list', id)
});
}
$(function(){
initializeDataTable(42);
});
</script>
To make sure that URLs are loaded correctly by django.js, listen for the ready
event:
// Wait for document ready
$(function(){
initializeDataTable(42);
});
// Wait for Django ready
Django.onReady(function(){
initializeDataTable(42);
});