我有一个包含ajax的javascript,它根据返回的数据刷新一个模板,如下所示-
产品-filter.js在代码下面
$(document).ready(function(){
$(".ajaxLoader").hide();
$(".filter-checkbox").on('click',function(){
var _filterObj={};
$(".filter-checkbox").each(function(index,ele){
var _filterVal=$(this).val();
var _filterKey=$(this).data('filter');
_filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){
return el.value;
});
});
//Run Ajax
$.ajax({
url:'/filter-data_b/1',
data: _filterObj,
dataType: 'json',
beforeSend: function(){
$(".ajaxLoader").hide();
},
success:function(res){
console.log(res);
$("#filteredProducts_b").html(res.data);
$(".ajaxLoader").hide();
}
})
});,我可以使用/filter-data_b/1,其中1是brand_id,它是硬编码的,我想知道如何从views.py中的/filter-data_b/1代码调用产品-filter.js的模板中获取它,urls.py如下所示
urls.py
urlpatterns = [
path('', views.home,name='home'),
path('brand_product_list/<int:brand_id>', views.brand_product_list,name='brand_product_list'),
path('filter-data_b/<int:brand_id>',views.filter_data_b,name='filter_data_b'),
]views.py是
def filter_data_b(request,brand_id):
colors=request.GET.getlist('color[]')
categories=request.GET.getlist('category[]')
brands=request.GET.getlist('brand[]')
sizes=request.GET.getlist('size[]')
flavors=request.GET.getlist('flavor[]')
allProducts=ProductAttribute.objects.filter(brand=brand_id).order_by('-id').distinct()
if len(colors)>0:
allProducts=allProducts.filter(productattribute__color__id__in=colors).distinct()
if len(categories)>0:
allProducts=allProducts.filter(category__id__in=categories).distinct()
if len(brands)>0:
allProducts=allProducts.filter(brand__id__in=brands).distinct()
if len(sizes)>0:
allProducts=allProducts.filter(productattribute__size__id__in=sizes).distinct()
if len(flavors)>0:
allProducts=allProducts.filter(productattribute__flavor__id__in=flavors).distinct()
t=render_to_string('ajax/product-list_b.html',{'data':allProducts})
return JsonResponse({'data':t})发布于 2021-10-26 10:29:24
--这是如何访问外部.js文件中的Django模板变量:
在模板中调用外部文件的
//顺序很重要,在尝试访问外部.js文件之前先声明变量,让object_id ={object_id} //假设'object_id‘在模板的上下文数据中。设url = {% url 'filter_data_b‘分支%}
$.ajax({ url: url,//上述. })
https://stackoverflow.com/questions/69721113
复制相似问题