简体   繁体   English

如何将javascript的JSON请求发布到Django并接收JSON答案?

[英]How to post JSON request from javascript to Django and receive an JSON answer?

My Django view: 我的Django视图:

class Main(View):
def post(self, request, *args, **kwargs):
    obj = json.loads(request.raw_post_data)
    //do something with obj
    temp = Entry.objects.all();
    result = []
    for t in temp:
        result.append( (t.key,t.value) );
    return HttpResponse(json.dumps(result), content_type="application/json")

My javascript: 我的JavaScript:

$.post("http://XXX/", JSON.stringify({}), function(data) {
              alert("OK");
            }, "json");

What firebug has to say: 萤火虫必须说的是:

POST http://193.0.96.129:8006/ 200 OK
Post Headers
Response headers
Content-Type    application/json
Date    Thu, 16 May 2013 00:00:28 GMT
Server  WSGIServer/0.1 Python/2.7.3
Request headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language pl,en-us;q=0.7,en;q=0.3
Content-Length  2
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    XXX
Origin  null
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0

The data gets through to Django, but the success callback doesn't get called. 数据到达Django,但未调用成功回调。 Django server returns code 200, but in Firebug notification about the POST is red. Django服务器返回代码200,但在Firebug中,有关POST的通知为红色。

I tried multiple variations of the $.post call, none worked. 我尝试了$ .post调用的多种变体,但没有奏效。 If I use $.ajax call and specify error callback 如果我使用$ .ajax调用并指定错误回调

error: function(xhr, textStatus, errorThrown) {
    alert("some error" + xhr.responseText+ " X " + textStatus + " X " + errorThrown);
},

all I get to know is that "error" happend (xhr.responseText == textStatus == "error"). 我所知道的是发生了“错误”(xhr.responseText == textStatus ==“错误”)。

It seems like I was trying to do a "Cross-Domain" call. 似乎我正在尝试进行“跨域”通话。 I was testing running the .html file locally, trying to call my remote Django server. 我正在测试本地运行.html文件的过程,试图调用远程Django服务器。 Changing path of POST destination to relative, and running the script through Django view fixed the problem. 将POST目标的路径更改为相对路径,并通过Django视图运行脚本解决了该问题。

Thank you Daniel, the Content-Length thing was my carelessness, I posted different view version then one that we see responding in Firebug (it was returning "{}" I think - I was trying to debug). 谢谢Daniel,Content-Length是我的粗心,我发布的视图版本与我们在Firebug中看到的视图版本不同(我认为它正在返回“ {}”-我正在尝试调试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM