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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - QueryDict always empty from AJAX POST

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...