Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have seen a few of these questions asked but I have tried to implement their solutions and it hasn't worked for me.

I am trying to send a basic AJAX request to a django view using POST. Here is my JQuery:

$('#save-button').click(function() {
    var names = ['BLOGGS Joe', 'SMITH John'];
    data = JSON.stringify(names);
    $.ajax({
        "contentType": "application/json; charset=utf-8",
        "data": data,
        "url" : "/ajax/myteam/save/",
        "type": "POST",
        "success": function(response) {

        }
    });
});

And here is my Django view:

def myteam_save(request):
   if request.method == 'POST':
       if request.POST:
           print 'Hurray'
       else:
           print 'Boo'
       response = HttpResponse(json.dumps({'code':'ok'}), content_type='application/json')
       return response

When I examine whats happening in Firebug I see that the post is being made as I intend but the QueryDict object from request.POST is always empty.

I have been careful about csrf tokens I think and even tried turning off the 'django.middleware.csrf.CsrfViewMiddleware' in my settings but this appears to have no effect.

What am I doing wrong?

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

Django doesn't really de-serialize JSON payloads for you. request.POST is meant to be used for HTML posted forms, and the like.

For JSON payloads, you should de-serialize the request body yourself, for example: json.loads(request.body).

(request.body is how you access the raw payload).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...