开发者

jQuery AJAX request gets called twice when using Jquery, Django and Google App Engine

开发者 https://www.devze.com 2023-01-15 13:41 出处:网络
I\'m using Google App Engine, Jquery and Django. I want POST data to be sent to the server side when a form is submitted, and I do this in JQuery with the following code:

I'm using Google App Engine, Jquery and Django. I want POST data to be sent to the server side when a form is submitted, and I do this in JQuery with the following code:

    $("#listform").submit(function() {
            $.ajax({
                    type: "POST",
                    url: "/xhrtest",
                    data: {'name': 'herman'},
                    success: function(data){
                            console.log(data)
                    }
            });
    })

In my Django view:

def xhrtest(request):
        if request.method == "POST":
                return HttpResponse("Post data!")
        else:
                return HttpResponse("GET request.")

I would have expected to receive a reply of "Post data!", but somehow the reply is always "GET request". This is not a unicode issue either, since one can print the request.method and see "GET".

When assessing this in Firebug, I see two requests going through: First a POST request, which receives the reply "GET request." and then a GET request, which receives the reply "Get request." as well. In the Google App Engine development console I can also see two requests going through. The POST request is met with a 301 response, and the GET wit开发者_开发知识库h 200.

What does this mean, and what do I have to do be able to receive POST data?


The problem is almost certainly that you are requesting the url /xhrtest, without a final slash. By default, Django will redirect that request to /xhrtest/ - with a final slash - and that redirection will be a GET, not a POST.

For more info, see the APPEND_SLASH setting that configures this behavior and CommonMiddleware module that uses it.


You need to "turn-off" your submit-button at first.

        $("#listform").off('submit').submit(function() {
                $.ajax({
                        type: "POST",
                        url: "/xhrtest",
                        data: {'name': 'herman'},
                        success: function(data){
                                console.log(data)
                        }
                });
        })

It works with click too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号