【问题标题】:Passing list of values to django view via jQuery ajax call通过jQuery ajax调用将值列表传递给django视图
【发布时间】:2012-06-25 22:57:17
【问题描述】:

我正在尝试使用 jQuery ajax 调用将数值 (id) 列表从一个网页传递到另一个网页。我不知道如何传递和读取列表中的所有值。我可以成功发布和读取 1 个值,但不能成功读取多个值。这是我目前所拥有的:

jQuery:

var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
    values = [1, 2];
    $.ajax({
        url: postUrl,
        type: 'POST',
        data: {'terid': values},
        traditional: true,
        dataType: 'html',
        success: function(result){
            $('#ingredients').append(result);
            }
    });       
});

/ingredients/ 视图:

def ingredients(request):
    if request.is_ajax():
        ourid = request.POST.get('terid', False)
        ingredients = Ingredience.objects.filter(food__id__in=ourid)
        t = get_template('ingredients.html')
        html = t.render(Context({'ingredients': ingredients,}))
        return HttpResponse(html)
    else:
        html = '<p>This is not ajax</p>'      
        return HttpResponse(html)

使用 Firebug,我可以看到 POST 包含两个 ID,但可能格式错误(terid=1&terid=2)。所以我的成分视图只选择 terid=2。我做错了什么?

编辑: 澄清一下,我需要将 ourid 变量传递值 [1, 2] 传递给成分视图中的过滤器。

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

    您可以在视图中通过request.POST.getlist('terid[]')访问这个数组

    在javascript中:

    $.post(postUrl, {terid: values}, function(response){
        alert(response);
    });
    

    在 view.py 中:

    request.POST.getlist('terid[]')
    

    它非常适合我。

    【讨论】:

    • selected = request.GET.getlist[‌​'selected[]'] TypeError: 'instancemethod' object has no attribute '__getitem__' 我收到此错误...但我有一系列类似 ["one","two","three"‌​] 的刺痛,并且正在使用GET 请求。 ..
    • 这行得通,但是……你为什么需要[]? django 文档根本没有引用它docs.djangoproject.com/en/3.0/ref/request-response/…
    • 非常有用,8 年后仍然有用!
    【解决方案2】:

    我找到了解决我最初问题的方法。在这里发布它作为答案,希望它可以帮助某人。

    jQuery:

    var postUrl = "http://localhost:8000/ingredients/";
    $('li').click(function(){
        values = [1, 2];
        var jsonText = JSON.stringify(values);
        $.ajax({
            url: postUrl,
            type: 'POST',
            data: jsonText,
            traditional: true,
            dataType: 'html',
            success: function(result){
                $('#ingredients').append(result);
                }
        });       
    });
    

    /ingredients/ 视图:

    def ingredients(request):
        if request.is_ajax():
            ourid = json.loads(request.raw_post_data)
            ingredients = Ingredience.objects.filter(food__id__in=ourid)
            t = get_template('ingredients.html')
            html = t.render(Context({'ingredients': ingredients,}))
            return HttpResponse(html)
        else:
            html = '<p>This is not ajax</p>'      
            return HttpResponse(html)
    

    【讨论】:

    • 仅供参考 - 一些较旧的浏览器没有内置 JSON 库。你可能最好使用$.serialize而不是JSON.stringify
    【解决方案3】:

    这部分是你的问题:

    ourid = request.POST.get('terid', False)
    ingredients = Ingredience.objects.filter(food__id__in=ourid)
    

    您需要反序列化 JSON 字符串。

    import json
    ourid = json.loads(request.POST.get('terid'))
    

    【讨论】:

    • 当我这样做时,我在 ajax 回调中收到此错误:TypeError at /ingredients/ 'int' object is not iterable
    【解决方案4】:

    您似乎在这里将数组设置为字符串

    data: {'terid': values},
    

    应该是

    data: {terid: values}
    

    【讨论】:

    • 仍然只拾取第二个值 (terid=2)。
    • Javascript 不在乎你在修改对象属性或字典键时是否使用引号。
    【解决方案5】:

    尝试像这样发送数据:

       data: values;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2020-08-31
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2018-08-23
      相关资源
      最近更新 更多