Passing list of values to django view via jQuery ajax call

前端 未结 5 690
一个人的身影
一个人的身影 2020-12-01 09:38

I\'m trying to pass a list of numeric values (ids) from one web page to another with jQuery ajax call. I can\'t figure out how to pass and read all the values in the list. I

相关标签:
5条回答
  • 2020-12-01 10:10

    You can access this array by request.POST.getlist('terid[]') in the view

    in javascript:

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

    in view.py:

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

    It works perfect for me.

    0 讨论(0)
  • 2020-12-01 10:15

    This part is your problem:

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

    You need to deserialize the JSON string.

    import json
    ourid = json.loads(request.POST.get('terid'))
    
    0 讨论(0)
  • 2020-12-01 10:20

    It seems you are setting the array to string here

    data: {'terid': values},
    

    It should be

    data: {terid: values}
    
    0 讨论(0)
  • 2020-12-01 10:27

    Try sending data like this:

       data: values;
    
    0 讨论(0)
  • 2020-12-01 10:29

    I found a solution to my original problem. Posting it here as an answer, hopefully it helps somebody.

    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/ view:

    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)
    
    0 讨论(0)
提交回复
热议问题