Django / Ajax - 如何根据选择过滤和显示结果 [英] Django / Ajax - How to filter and display result based on selection

查看:61
本文介绍了Django / Ajax - 如何根据选择过滤和显示结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to filter and display data in Django based on the selection made by the user from drop down box. I'm using ajax call to send a request to Django views. When a user selects, for example, Airline A, then Ajax will send the 'value' of that selection which is an integer to Django backend to filter data and send it back to frontend. Here is my code:

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>

Ajax:

<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(数据)显示一个空数组,表示视图未被过滤。如何根据用户的选择过滤和显示数据?

My console.log(data) is showing an empty Array which means views are not getting filtered. How can I filter and display the data based on the selection made by the user?

推荐答案

尝试修改 ajax 添加数据变量的代码。

try to modify your ajax code to add a data variable.

$.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)
     }
});

这篇关于Django / Ajax - 如何根据选择过滤和显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆