我使用 AJAX 过滤过滤我的产品的颜色,品牌,大小。数据过滤成功,但它显示的一切。我希望您的帮助,并感谢您的关注
Trying to filter products...
product-filter.js:20 {data: '\n\n \n <div class="col-md-4 mb-0">\n … </div>\n </div>\n </div>\n \n'}data: "\n\n \n <div class=\"col-md-4 mb-0\">\n[[Prototype]]: Object
product-filter.js:21 Data filtered successfully
AJAX
$(document).ready(function(){
$(".filter-checkbox").on('click', function(){
let filter_object = {};
$(".filter-checkbox").each(function(index,ele){
let filter_value = $(this). val();
let filter_key=$(this). data('filter');
filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(element){
return element.value;
});
});
$.ajax({
url:'/filter_products',
data:filter_object,
dataType:'json',
beforeSend:function(){
console.log('Trying to filter products...');
},
success:function(response){
console.log(response);
console.log('Data filtered successfully');
$("filteredProducts").html(response.data)
}
});
});
});
views.py
def filter_products(request):
color = request.GET.getlist('color[]')
brand = request.GET.getlist('brand[]')
size = request.GET.getlist('size[]')
products = Product.objects.all().order_by('-id').distinct()
if len(color)>0:
products=products.filter(color__id__in=color).distinct()
if len(brand)>0:
products=products.filter(brand__id__in=brand).distinct()
if len(size)>0:
products=products.filter(size__id__in=size).distinct()
t = render_to_string('ajax/product-list.html',{'products':products})
return JsonResponse({'data':t})
def search(request):
data1 = wishData(request)
wishItems = data1['wishItems']
data = cartData(request)
q = request.GET['q']
cartItems = data['cartItems']
products = Product.objects.filter(name__icontains=q).order_by('id')
context = {'products': products, 'cartItems': cartItems,'wishItems': wishItems}
return render(request, 'store/store.html', context)
def product_view(request, id):
product = Product.objects.filter(id=id).first()
data = cartData(request)
cartItems = data['cartItems']
data1 = wishData(request)
wishItems = data1['wishItems']
context = {'product':product, 'cartItems':cartItems, 'wishItems':wishItems}
return render(request, 'store/product_view.html', context)
def store(request):
data1 = wishData(request)
wishItems = data1['wishItems']
data = cartData(request)
cartItems = data['cartItems']
products = Product.objects.all()
color = Color.objects.all()
size = Size.objects.all()
brand = Brand.objects.all()
price = Product.objects.values_list('price')
context = {'products':products, 'cartItems':cartItems, 'wishItems':wishItems,'color':color, 'size':size, 'brand':brand, 'price':price}
return render(request, 'store/store.html', context)
urls.py
urlpatterns = [
path('', views.store, name="store"),
path('cart/', views.cart, name="cart"),
path('checkout/', views.checkout, name="checkout"),
path('login/', views.loginPage, name="login"),
path('logout/', views.logoutUser, name="logout"),
path('registration/', views.registrationPage, name="registration"),
path('profile/', views.profile, name="profile"),
path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"),
path('change_password/profile/', views.profile, name="profile"),
path('filter_products/', views.filter_products, name="filter_products"),
path('update_item/', views.updateItem, name="update_item"),
path('update_wish_item/', views.updateWishItem, name="update_wish_item"),
path('process_order/', views.processOrder, name="process_order"),
path('wishlist/', views.wishlist, name="wishlist"),
path('search/', views.search, name="search"),
path('<int:id>', views.product_view, name="product_view"),
path('search/<int:id>',views.product_view, name="product_view"),
]
product-list.html
{% for product in products %}
<div class="col-md-4 mb-0">
<div class="card" style="width: 17rem; margin:40px;">
<img class="card-img-top" src="{{product.imageURL}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"><strong>{{product.name}}</strong></h5>
<button data-product="{{product.id}}" data-action="add" class="btn btn-outline-dark add-btn update-cart" data-bs-toggle="popover" data-bs-placement="top" >Add to Cart</button>
<a class="btn btn-outline-dark" href="{{product.id}}">View</a>
<button data-product={{product.id}} data-action="add" data-toggle="button" aria-pressed="false" autocomplete="off" class="btn btn-outline-danger add-btn update-wishlist" style="margin-left:19px;">♡</button>
<h4 style="display: inline-block; float: right"><strong>{{product.price}} ₽</strong></h4>
</div>
</div>
</div>
filters.html
{% load static %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="{% static 'js/product-filter.js' %}"></script>
<h3 class="mb-4 border-bottom pb-4">Filters</h3>
<!-- Price Filter -->
<div class="card mb-10" style="margin-top:50px;">
<h6 class="card-header">Price</h6>
<div class="list-group list-group-flush">
<li class="list-group-item">
<input type="range" value="{{minMaxPrice.price__min}}" max={{minMaxPrice.price__max}} min={{minMaxPrice.price__min}} id="rangeInput" oninput="maxPrice.value=this.value" />
<p>{{minMaxPrice.price__min}}-{{minMaxPrice.price__max}}</p>
</li>
<li class="list-group-item">
Max: <input type="number" value="{{minMaxPrice.price__min}}" max={{minMaxPrice.price__max}} min={{minMaxPrice.price__min}} class="form-control" id="maxPrice" onkeyup="rangeInput.value=this.value" id="maxPrice" />
<button id="priceFilterBtn" class="btn btn-info btn-sm mt-1">Filter</button>
</li>
</div>
</div>
<!-- Filter 1 -->
<div class="card mb-4">
<h6 class="card-header">Colors</h6>
<div class="list-group list-group-flush">
{% for colors in color %}
<li class="list-group-item">
<input class="filter-checkbox" data-filter="color" value="{{colors.id}}" type="checkbox" />
<button class="btn" style="background-color: {{colors.color_code}}; margin-top: -5px;box-shadow: 0 0 1px 0 ;"></button>
{{colors.title}}
</li>
{% endfor %}
</div>
</div>
<div class="card mb-4">
<h6 class="card-header">Brands</h6>
<div class="list-group list-group-flush">
{% for brands in brand %}
<li class="list-group-item">
<input class="filter-checkbox" data-filter="brand" value="{{brands.id}}" type="checkbox" />
{{brands.title}}
</li>
{% endfor %}
</div>
</div>
<!-- Filter 3 -->
<div class="card mb-4">
<h6 class="card-header">Sizes</h6>
<div class="list-group list-group-flush">
{% for sizes in size %}
<li class="list-group-item">
<input class="filter-checkbox" data-filter="size" value="{{sizes.id}}" type="checkbox" />
{{sizes.title}}
</li>
{%endfor%}
</div>
</div>
store.html
{% extends 'store/main.html' %}
{%load static%}
{% block content %}
<main class="container my-5">
<div class="row">
<div class="col-md-3" >
{% include 'store/filters.html' %}
</div>
<div class="col-md-9">
<!-- Products -->
<h3 class="mb-9 border-bottom pb-4" style="margin-left:40px;">
Products
</h3>
<div class="row" id="filteredProducts">
{% for product in products %}
<div class="col-md-4 mb-0">
<div class="card" style="width: 17rem; margin:40px;">
<img class="card-img-top" src="{{product.imageURL}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"><strong>{{product.name}}</strong></h5>
<button data-product="{{product.id}}" data-action="add" class="btn btn-outline-dark add-btn update-cart" data-bs-toggle="popover" data-bs-placement="top" >Add to Cart</button>
<a class="btn btn-outline-dark" href="{{product.id}}">View</a>
<button data-product={{product.id}} data-action="add" data-toggle="button" aria-pressed="false" autocomplete="off" class="btn btn-outline-danger add-btn update-wishlist" style="margin-left:19px;">♡</button>
<h4 style="display: inline-block; float: right"><strong>{{product.price}} ₽</strong></h4>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</main>
{% endblock %}
和一些models.py
class Product(models.Model):
gender_choices = [('Male', 'Male'), ('Female', 'Female')]
name = models.CharField(max_length=200)
detail = models.TextField()
color = models.ForeignKey(Color, on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
size = models.ForeignKey(Size, on_delete=models.CASCADE, blank=True, null=True)
gender = models.CharField(max_length=6, choices=gender_choices, default='Male')
price = models.DecimalField(max_digits=10, decimal_places=0)
status = models.BooleanField(default=True,null=False, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Brand(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.title
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Size(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class Color(models.Model):
title = models.CharField(max_length=100)
color_code = models.CharField(max_length=100)
def __str__(self):
return self.title
我想同时通过几个参数过滤我的产品
1条答案
按热度按时间fhity93d1#
你错过了jQuery选择器的一部分。它是一个有ID的元素,所以你需要在它前面加上# - Try: