Django / Ajax - 如何根据选择过滤和显示结果

问题描述 投票:0回答:2

我正在尝试根据用户从下拉框中所做的选择在 Django 中过滤和显示数据。我正在使用 ajax 调用向 Django 视图发送请求。例如,当用户选择航空公司 A 时,Ajax 会将该选择的“值”(一个整数)发送到 Django 后端以过滤数据并将其发送回前端。这是我的代码:

HTML:

<form method="GET">
    <select id="airline-selected">
        {% for airline in airline_list %}
            <option value="{{ airline.id }}">
            {{ airline.name }}
            </option>
        {% endfor %}
    </select>
    <input type="button" value="Update" id="selection-button" method="GET">
</form>

阿贾克斯:

<script>
        $( "#selection-button" ).click(function(event) {
            event.preventDefault();
            var airlineSelected = $('#airline-selected').find(":selected").val();

            $.ajax({
                url: "{% url 'charts_data' %}",
                method: 'GET',
                filter_category: parseInt(airlineSelected),
                success: function(data){
                console.log(data)
         },
                error: function(error_data){
                console.log("error")
                console.log(error_data)
         }
            })
        });
    </script>

Views.py:

class ChartData(generics.ListAPIView):
    serializer_class = FinancialDataSerializer

    def get_queryset(self, *args, **kwargs):
        filter_category = self.request.GET.get("filter_category")
        queryset = FinancialData.objects.filter(airline_id=filter_category)
        queryset_filtered = queryset.filter()
        return queryset_filtered

我的 console.log(data) 显示一个空数组,这意味着视图没有被过滤。如何根据用户的选择过滤和显示数据?

jquery python ajax django
2个回答
7
投票

尝试修改您的

ajax
代码以添加
data
变量。

$.ajax({
     url: "{% url 'charts_data' %}",
     method: 'GET',
     data : {
             filter_category: parseInt(airlineSelected)
     }
     success: function(data){
         console.log(data)
     },
     error: function(xhr, errmsg, err){
         console.log("error")
         console.log(error_data)
     }
});

0
投票
<select id="teacherSelect">
    <option value="">Select a teacher</option>
    {% for teacher in teachers %}
        <option value="{{ teacher.id }}">{{ teacher.name }}</option>
    {% endfor %}
</select>

<div id="subjectSelect">
   
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    // Use jQuery for simplicity (make sure you have jQuery loaded)
    $(document).ready(function() {
        $('#teacherSelect').change(function() {
            var teacherId = $(this).val();

            $.ajax({
                url: '{% url "filter_subjects_by_teacher" %}',
                data: { teacher_id: teacherId },
                dataType: 'json',
                success: function(data) {
                    var subjectSelect = $('#subjectSelect');
                    subjectSelect.empty();

                    if (data.subjects.length === 0) {
                        subjectSelect.append('<option value="">No subjects available</option>');
                    } else {
                        $.each(data.subjects, function(index, subject) {
                            subjectSelect.append('<option value="' + subject + '">' + subject + '</option>');
                        });
                    }
                },
                error: function() {
                    console.log('Error in the AJAX request');
                }
            });
        });
    });
    
</script>
and the views is 




def filter_subjects_by_teacher(request):
    teacher_id = request.GET.get('teacher_id')
    if teacher_id:
        teacher = Teacher.objects.get(pk=teacher_id)
        subjects = teacher.subject.all()
        subject_names = [subject.name for subject in subjects]
        return JsonResponse({'subjects': subject_names})
    else:
        return JsonResponse({'subjects': []})
© www.soinside.com 2019 - 2024. All rights reserved.