Send a list to django within an ajax GET request

I found a lot of posts here and outside talking about this problem but with POST request.

THIS IS THE PROBLEM: I have a list in my javascript and I need to send that list to django view as argument.

Javascript

 $.ajax({
    url: "myMethod",
    type: "GET",
    data: {"par1":par1,"par2":par2,"list":list},
    cache: false,
    success: function(d){
      // DO SOMETHING
    }
}

Python code (views.py)

def myMethod(request):
    par1 = request.GET.get('par1')
    par1 = request.GET.get('par2')
    list = request.GET.get('list') # DON'T WORK
    #OR
    list = request.GET.getlist('list') # DON'T WORK
    #OR
    list = request.GET.getlist('list[]') # DON'T WORK
    result = DO_SOMETHING(par1,par2,list)
    return result

I tried three ways that I found in other posts but none was working.

Answer

Could you join the list before posting and the split it in your django view?

Javascript

$.ajax({
    url: "myMethod",
    type: "GET",
    data: {"par1":par1,"par2":par2,"list":list.join("-and-")},
    cache: false,
    success: function(d){
      // DO SOMETHING
    }
}

Python code (views.py)

def myMethod(request):
    par1 = request.GET.get('par1')
    par1 = request.GET.get('par2')
    list = request.GET.get('list').split('-and-')

    result = DO_SOMETHING(par1,par2,list)
    return result

Leave a Reply

Your email address will not be published. Required fields are marked *