簡體   English   中英

JSON POST中的Django請求出現問題

[英]Issue with my Django request from a JSON POST

我嘗試訪問一個JSON對象,該對象從JS-jquery用$ .post發送到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_brief_write.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

如果按提交按鈕,則將正確顯示“完成”警報,但是mongoDB中的集合中沒有任何內容。

如果我用測試代替t

post_id = collection.insert(test)

我也有完成警報,並且在mongo DB集合中創建了我的對象。

我的錯誤在哪里? 在我的POST請求中? 我在Apache下工作,並且使用modpython。

看起來是由於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_events_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 

親愛的@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按鈕時,我收到“不是POST請求”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM