我正在尝试根据用户从下拉框中所做的选择来过滤和显示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)显示了一个空数组,这意味着视图没有被过滤.如何根据用户的选择过滤和显示数据?
解决方法:
$.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)
}
});