简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM