我有一個包含 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 從 /filter-data_b/ 呼叫1.views.py和urls.py中的代碼如下圖
網址.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})
uj5u.com熱心網友回復:
這是訪問外部 .js 檔案中的 Django 模板變數的方法:
在您呼叫外部 .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>在您的外部 .js 檔案中
$.ajax({ url: url, // Declared above ... })
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338071.html
上一篇:通過AJAX回傳坐標
