在我的 Django 项目中,我有一个基本视图,我在其中传递 Article 模型的所有实例,然后使用 for 循环将它们显示在 HTML 模板中。我还有一个主题模型,因此我将所有主题显示为按钮,也带有 for 循环。我的目标是通过单击特定主题按钮来过滤文章,因此,例如,如果我单击“政治”,则只会显示与“政治”主题相关的文章,而不是所有文章。我想为此使用 AJAX 请求,但我没有这方面的经验,所以我在弄清楚如何实现我的目标时遇到了一些问题。
这是我的观点。我正在尝试在同一个视图中执行 AJAX,但我不确定这是否正确,因为在我看到的大多数情况下,创建了一个单独的视图:
def main_view(request):
all_articles = Article.objects.all()[::-1]
top_articles = all_articles[:10]
topics = Topic.objects.all()
if request.is_ajax():
topic_name = request.GET.get('topic_name')
all_articles = Article.objects.filter(topics=topic_name)
return JsonResponse({'all_articles': all_articles})
return render(request, "mainapp/main_refactor.html", {"all_articles": all_articles, "top_articles": top_articles, "topics": topics})
简化的 HTML 模板:
{% for topic in topics %}
<button class="topic-button" data-url="{% url 'mainapp:filter_articles' topic.name %}"
data-topic-name="{{ topic.name }}">{{ topic.name }}</button>
{% endfor %}
<section id="article-list" class="new-articles">
{% for article in all_articles %}
{{ article.body }}
{% endfor %}
和 AJAX 代码:
$(document).ready(function () {
$('.topic-button').click(function () {
var topicName = $(this).data('topic-name');
var url = $(this).data('url'); // tried to add separate URLs for each Topic filtering, but abandoned it for now, so everything is in one view
console.log(url);
$.ajax({
url: '',
method: 'GET',
data: {'topic_name': topicName},
success: function (response) {
console.log(response + " I have no idea what to code here");
},
});
});
});
上面的代码是我现在所在的位置。如果能够为带有 url“/topic/str:topic_name”的 ajax 请求提供单独的视图,那将是完美的。感谢您提前的帮助。
您应该有一个单独的过滤器端点
def filter_articles(request):
topic_name = request.GET.get('topic_name')
if topic_name:
articles = Article.objects.filter(topics__name=topic_name)
return JsonResponse({'all_articles': articles}) # Serialize articles for JSON response
else:
return JsonResponse({'error': 'No topic provided'})
网址
path('filter_articles/', views.filter_articles, name='filter_articles')
对于html部分你可以这样做
{% for topic in topics %}
<button class="topic-button" data-topic-name="{{ topic.name }}">{{ topic.name }}</button>
{% endfor %}
<section id="article-list" class="new-articles">
</section>
<script>
$(document).ready(function () {
$('.topic-button').click(function () {
var topicName = $(this).data('topic-name');
$.ajax({
url: '{% url 'mainapp:filter_articles' %}', // Use reverse URL lookup
method: 'GET',
data: {'topic_name': topicName},
success: function (response) {
if (response.error) {
console.error(response.error);
return;
}
// Here's an example
$('#article-list').empty(); // Clear the current articles
response.all_articles.forEach(function(article) {
$('#article-list').append('<div>' + article.body + '</div>');
});
},
});
});
});
</script>