2014-01-30 17 views

回答

4

request.POST由django預處理,所以你想要的是request.body。使用JSON解析器來解析它。

import json 

def do_stuff(request): 
    if request.method == 'POST': 
    json_data = json.loads(request.body) 
    # do your thing 
+0

這導致'TypeError:JSON對象必須是str,而不是'bytes''在Python 3 – gtd

+1

@ gtd謝謝!你需要先解碼它:'json.loads(request.body.decode(「utf-8」))';有關更多詳細信息,請參閱http://stackoverflow.com/questions/29514077/get-request-body-as-string-in-django。 –

2

發送給使用HttpResponse無需刷新網頁瀏覽器的響應。

views.py

from django.shortcuts import render, HttpResponse, 

import simplejson as json 

def json_rest(request): 
    if request.method == "POST": 
     return HttpResponse(json.dumps({'success':True, 'error': 'You need to login First'})) 
    else: 
     return render(request,'index.html') 

urls.py

(r^'/','app.views.json_rest') 

客戶端:

$.ajax({ 
    type:"post", 
    url: "/", 
    dataType: 'json', 
    success: function(result) { 
     console.log(result)  

     } 
}); 
+0

您正在討論回覆。爲響應我具有以下機構: \t'@json \t DEF feed_one(請求,ID): \t \t樣品= get_object_or_404(樣品,PK = ID) \t \t返回sample' –

+0

哪裏@json是裝飾和外觀是這樣的: '高清JSON(FN): \t高清封裝(請求,* ARGS,** kwargs): \t \t嘗試: \t \t \t fn_result = FN(請求,* ARGS,** kwargs) \t \t \t json_result = { 'is_successful':真, '消息':無, '數據':fn_result} \t \t除了例外爲e: \t \t \t如果DEBUG: \t \t \t \t加註Ë \t \t \t json_result = { 'is_successful':假, '消息':e.message, '數據':無} \t \t返回的HttpResponse(to_json(json_result),MIME類型= '應用/ JSON') \t返回wrapper' 現在我正在寫響應hadnling機制,並需要類似上面代碼的東西。 –

+0

@KenanBek我已更新我的編輯 – dhana

相關問題