除非jQuery.ajaxSettings.traditional = true,否则jango的Django验证失败;

时间:2013-07-20 09:29:49

标签: jquery python django json validation

所以我有一个AJAX发布JSON到Django,在我的视图中在request.body中获取。 Request.body看起来像这样:

{"c": {"cellid": 5}, "b": {"cellid": 8}, "e": {"cellid": 3}, "i": {"cellid": 9}, "k": {"cellid": 11}, "j": {"cellid": 10}, "l": {"cellid": 12}, "n": {"cellid": 7}, "q": {"cellid": 1}, "r": {"cellid": 4}, "w": {"cellid": 2}, "v": {"cellid": 6}}

我想将此作为验证和清理过程的JSON对象,但是,当我尝试:

json.loads(request.body)
ValueError: No JSON object could be decoded

和SimpleJSON说:

simplejson.loads(request.body)
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

关于出了什么问题的任何指示?当我JSON lint上面它是有效的,那么解码的问题是什么?

有趣的是,从this question来看,这似乎是jQuery的错误,如

jQuery.ajaxSettings.traditional = true;

修复了javascript中的问题。我不确定为什么会这样,有什么想法?

1 个答案:

答案 0 :(得分:0)

views.py

from django.template.loader import render_to_string
from django.utils import simplejson
if form.is_valid():
template = "my_template.html"
html = render_to_string(template,{"c": {"cellid": 5}, "b": {"cellid": 8}, "e": {"cellid": 3}, "i": {"cellid": 9}, "k": {"cellid": 11}, "j": {"cellid": 10}, "l": {"cellid": 12}, "n": {"cellid": 7}, "q": {"cellid": 1}, "r": {"cellid": 4}, "w": {"cellid": 2}, "v": {"cellid": 6}})
response = simplejson.dumps({'success':'True','html':html})

try it, it should work.