使用jQuery、Django和谷歌应用程序引擎时,会调用jQuery AJAX请求两次

时间:2022-09-15 11:49:30

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:

我使用的是谷歌应用引擎,Jquery和Django。我希望在提交表单时将数据发送到服务器端,我用JQuery编写如下代码:

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

In my Django view:

在我的Django视图:

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

我本以为会收到“邮寄资料!”,但不知何故,回复总是“GET request”。这也不是unicode问题,因为可以打印请求。方法,看看“获得”。

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 with 200.

当在Firebug中评估这一点时,我看到有两个请求正在进行:首先是一个POST请求,它接收到回复“GET request”,然后是一个GET请求,它也接收到回复“GET request”。在谷歌应用程序引擎开发控制台,我还可以看到两个请求正在通过。POST请求得到301响应,得到200。

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

这意味着什么,我需要做什么才能收到POST数据?

1 个解决方案

#1


11  

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.

几乎可以肯定的是,您正在请求url /xhrtest,而没有最后的斜杠。默认情况下,Django将把请求重定向到/xhrtest/——最后一个斜线——重定向将是GET,而不是POST。

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

有关更多信息,请参见配置此行为的APPEND_SLASH设置和使用该行为的CommonMiddleware模块。

#1


11  

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.

几乎可以肯定的是,您正在请求url /xhrtest,而没有最后的斜杠。默认情况下,Django将把请求重定向到/xhrtest/——最后一个斜线——重定向将是GET,而不是POST。

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

有关更多信息,请参见配置此行为的APPEND_SLASH设置和使用该行为的CommonMiddleware模块。