我的Django请求来自一个JSON帖子

2024-04-24 04:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试访问一个JSON对象,它是用$.post从JS jquery发送到Django脚本的

我尝试了在Stackoverflow上看到的许多东西的组合,但我无法使其工作:

在.js方面:

$("#submitbtn").click(function() {
    var payload = {"name":"Richard","age":"19"};
    $("#console").html("Sending...");
    $.post("/central/python/mongo_brief_write.py",{'data': JSON.stringify(payload)},
                                           function(ret){alert(ret);});
    $("#console").html("Sent.");
});

我剧本的内容叫mongoèu brief_写入.py是:

#!/usr/bin/env python
import pymongo
from pymongo import Connection
from django.utils import simplejson as json

def save_events_json(request):
    t = request.raw_post_data
    return t

con = Connection("mongodb://xxx.xxx.xxx.xxx/")
db = con.central
collection = db.brief
test = {"name":"robert","age":"18"}
post_id = collection.insert(t)

def index(req):
    s= "Done"
return s

如果按submit按钮,则会正确显示“Done”警报,但mongoDB中的集合中没有任何内容。你知道吗

如果我用测试代替t

post_id = collection.insert(test)

我也做了警报,我的对象是在我的mongodb集合中创建的。你知道吗

我的错在哪里?在我的邮件请求中?我在Apache下工作,我使用modpython。你知道吗


Tags: 对象nameimportjsonagemongohtmlfunction
2条回答

亲爱的@Kyrylo Perevozchikov,我已经更新了我的代码:

import pymongo
from pymongo import Connection
from django.utils import simplejson as json
from django.http import HttpResponse,HttpRequest
request = HttpRequest()
if request.method == 'POST':
    def index(request):
        global t
        t = request.raw_post_data                          
  post_id=Connection("mongodb://xxx.xxx.xxx.xxx/").central.brief.insert(t)
        return HttpResponse(content=t)
else:
    def index(req):
        s="Not A POST Request"
        return s

当我点击jquery按钮时,我看到了“nota POST Request”

看起来它的发生是因为python名称空间规则。如果在函数中定义变量:

>>>def random_func(input):
       t = input
       return t
>>>t
Traceback (most recent call last): File "<input>", line 1, in <module> 
NameError: name 't' is not defined

它不会是全局变量。 所以,你需要做的是: 首先,将带有基本操作的代码放入函数save\u events\u json中:

def save_events_json(request):
    t = request.raw_post_data
    con = Connection("mongodb://xxx.xxx.xxx.xxx/")
    db = con.central
    collection = db.brief
    test = {"name":"robert","age":"18"}
    post_id = collection.insert(t)
    from django.http import HttpResponse
    return HttpResponse(content=t)

或将变量“t”设置为全局:

def save_events_json(request):
    global t
    t = request.raw_post_data
    return t 

相关问题 更多 >