2017-04-08 97 views
0

我有以下脚本:Django的 - 通过一个jQuery数组作为url参数

jQuery(document).ready(function($) { 
    $("#continue").click(function() { 
     var selected = $("#meds").bootgrid("getSelectedRows"); 
     window.location = "{% url 'meds:prescription' selected %}" 
    }); 
}); 

和这样的观点:

class PrescriptionView(generic.ListView): 
    template_name = 'meds/prescription.html' 
    context_object_name = 'meds' 
    model = Medicament 

    def get_queryset(self): 
     return Medicament.objects.filter(id__in=self.kwargs['selected']) 

与此URL:

url(r'^prescription/(?P<selected>.*)/$', views.PrescriptionView.as_view(), name='prescription') 

知道所选是一个数组,例如[3, 6, 4]我试图用它来显示与该数组中的id对象,但由于某种原因,即使当数组完全没有在URL中传递,它只是看起来像这样一个空白页面http://127.0.0.1:8000/prescription//,就像参数没有通过

回答

1

这是因为selected变量被解析为一个Django模板变量,但事实上并非如此。它是一个JS变量,因此它被解析为一个空字符串。

有一种变通方法,但:

jQuery(document).ready(function($) { 
    $("#continue").click(function() { 
     var selected = $("#meds").bootgrid("getSelectedRows"); 
     var url = "{% url 'meds:prescription' 'test' %}"; // 'test' is just a placeholder value 
     url = url.replace('test', selected); // replace 'test' with the 'selected' value 
     window.location = url; 
    }); 
}); 
+0

完美的作品!非常感谢! – Meryem