2014-02-21 29 views
0

我嘗試進入一個JSON對象,由JS-發送的jQuery與$。員額爲腳本的Django Django的我的要求,問題從一個JSON POST

我嘗試了很多事情,我就看到了#1相結合,但我不能讓它工作:

在.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中。

如果我在

post_id = collection.insert(test) 

t替換爲通過測試,我已經做了太多戒備,在我的蒙戈DB集合創建我的對象。

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

回答

1

看起來像是因爲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 
+0

親愛的@Kyrylo Perevozchikov,thx爲您的幫助, 我明白你的觀點與全球變種,這是有道理的,但它不能解決我的問題不幸。 我不明白的是,如果我刪除我的.py腳本的這一部分: def index(req): s =「完成」 返回s,將所有行放在同一個save_events_json函數中,返回t at最後,我有一個POST 500內部服務器錯誤? – Manuhoz

+0

親愛的@Manuhoz,它因爲你沒有返回HttpResponse對象,所以試着從「django.http import HttpResponse」,「return HttpResponse(content = t)」 –

+0

我發送了更多的細節以正確格式化代碼thx @Kyrylo Perevozchikov – Manuhoz

0

親愛@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請求」