如何在javascript中使用Django模板访问ajax jquery中的模板变量



我有一个包含ajax jquery的javascript,它根据返回的数据刷新模板,如下所示-

product-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,我想知道如何从模板中得到这个product-filter.js被调用views.py和urls.py中的/filter-data_b/1代码如下所示

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})

在外部.js文件中访问Django模板变量的方法如下:

  1. 在你调用外部.js文件的模板中

    // The order is matter, declare the variable before try to access in your external .js file
    <script>
    let object_id = {{object_id}}  // Assume that 'object_id' is in the the context data of the template.
    let url = {% url 'filter_data_b' brandid %}
    </script> 
    <script src="{% static 'product-filter.js' %}"></script>
    
  2. 在你的外部。js文件

    $.ajax({
    url: url, // Declared above
    ...  
    })
    

最新更新