Django: reconstruct structured parameters sent via $.post

前端 未结 3 2052
忘掉有多难
忘掉有多难 2021-02-02 04:49

I\'m sending an Ajax request (with jQuery) with structured post data:

$.post(
    myUrl,
    {
         items: [{code: \'a\', description: \'aaa\'},
                     


        
相关标签:
3条回答
  • 2021-02-02 05:10

    I made special library for Django/Python to handle structured data sent through requests. You can find it on GitHub here.

    0 讨论(0)
  • 2021-02-02 05:19

    I'd suggest you post your object as JSON. In Django, you then can recreate the structure by parsing the JSON into python objects.

    Post JSON with jQuery

    $.post(
        myUrl,
        JSON.stringify({
             items: [{code: 'a', description: 'aaa'},
                    {code: 'b', description: 'bbb'}]
        })
    )
    

    Parsing JSON in Django view

    from django.http import HttpResponse
    from django.utils import simplejson
    
    def my_view(request):
        if request.method == 'POST':
            json_data = simplejson.loads(request.raw_post_data)
            # json_data contains your objects
            print json_data['items']
    
        return HttpResponse("Got data")
    
    0 讨论(0)
  • 2021-02-02 05:22

    You could try:

    request.POST.getlist('items')
    
    0 讨论(0)
提交回复
热议问题