2011-09-19 70 views
0

回來,我在這裏做一個非常簡單的事情,做一個POST請求從jQuery來Django的,和我得到一個奇怪的錯誤了一個非常簡單的場景。我有以下看法功能:的jQuery parsererror從Django的

from django.views.generic.simple import direct_to_template as dto 

def do_login(request): 
    if request.method == "POST": 
     return dto(request, "path/to/template.json", { 
      'success': False, 
      'cause': None 
     }, mimetype="text/json") 

這裏是我的模板:

{ success : {{success|lower}}{% if cause %}, cause : {{cause}}{% endif %} } 

...這是我的jQuery:

$.ajax("/login/", { type: "POST", 
    data: $("#loginForm").serialize(), 
    success: function(data) { 
     console.log("login response: " + data); 
    }, 
    error: function(data, stats, error) { 
     console.log("login fault: " + data + ", " + 
       stats + ", " + error); 
    } 
}); 

很簡單,不是嗎?以下是我在控制檯中得到的結果:

login fault: [object Object], parsererror, SyntaxError: Unexpected token s 

這裏怎麼回事?如果我沒有設置我的渲染方法mimetype,然後一切工作正常。問題是,我想返回JSON而不必強制jQuery重新解析它。任何人都可以在這裏發現我的錯我似乎無法看到它。

回答

2

的JSON是無效的。您需要周圍的標識符引號,所以"success"代替success"cause"而不是cause

+0

謝謝,固定它。我不知道這是必需的,因爲在JS'{成功:真正}'是一樣的'{「成功」:真正}'。 –

1
from django.utils import simplejson as json 

def do_login(request): 
    if request.method == "POST": 
     return HttpResponse(json.dumps({'success': False, 'cause': None}), content_type='application/json') 
+0

超級有用,謝謝。這使事情變得更容易,意味着我不必爲它編寫模板。 –