【问题标题】:How do I get the data send by Ajax in Django?如何在 Django 中获取 Ajax 发送的数据?
【发布时间】:2021-09-26 15:07:42
【问题描述】:

我尝试使用 request.GET.get 获取通过 Ajax 发送的数据,但这不起作用。数据始终为无。我非常感谢任何形式的帮助!

这是我的 jQuery/Ajax 代码:

$(document).ready(function(){
        $(".jcf-select.jcf-unselectable").on('click', function(){
            var sel = $('#sort').children("option:selected").val();
            console.log(sel)

        $.ajax({
            url: '/filter-data',
            data: sel,
            dataType: 'json',
            success:function(res){
                console.log(res);
                $("#filter_products").html(res.order);
            }
        });
        });
    });

这是我的看法:

def filter_data(request):
    if request.is_ajax:
        query = []
        data = request.GET.get('data')
    
        if data == "gpv":
            query = data.order_by("price_with_shipping")[:150]

        elif data == "gp":
            query = data.order_by("lowest_price")[:150]

        elif data == "lp":
            query = data.order_by("liter_price")[:150]

        elif data == "tz":
            query = data.order_by("-lowest_price")[:150]

        t = render_to_string('homepage/ajax-products.html', {'order': query})

        return JsonResponse({'order': t})

【问题讨论】:

    标签: python django ajax


    【解决方案1】:

    data 必须是 ajax 中的对象。 例如:

        $.ajax({
            url: '/filter-data',
            data: {'key-data':sel},
            dataType: 'json',
            success:function(res){
                console.log(res);
                $("#filter_products").html(res.order);
            }
    

    在你的 django 视图中:

    data = request.GET.get('key-data')
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2012-11-23
      • 2016-06-07
      • 2016-08-07
      • 2013-09-11
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多