in html
<div class="reply-writer" >
<input type="reply" data-id="{{res.id}}" name="comment" class="form-control reply-input">
</div>
在jquery中
$(document).on( "keypress", "input.reply-input",function(e) {
if (e.which == 13) {
var id =$(this).data("id");
var cmt = $(this).val();
var url="http://xxx/comment";
var data = {
'res_id': id,
'comment': cmt,
};
$.ajax({
type: "POST",
url: url,
data: data,
async:false
}).done(function( items ) {
alert("done");
}
);
}
});
在views.py中
def comment(request):
print request
print "comment" + str(request.POST)
response_data = None
try:
res_id = request.POST.get(u'res_id', 0)
comment = request.POST.get(u'comment', None)
super = request.POST.get(u'super', 0)
comment = comment.encode('utf-8')
if res_id !=0 or comment:
res = Restaurant.objects.filter(id=res_id)[0]
cmt = Comment(user=request.user, comment=comment, super=super, restaurant=res)
cmt.save()
current_cmt = Comment.objects.filter(id=cmt.pk)
response_data = current_cmt
else:
response_data = {}
except Exception as e:
logging.exception(e)
raise Http404
print "response_data:"+str(response_data)
return HttpResponse(json.dumps(response_data), content_type="application/json")
控制台日志中的
comment<QueryDict: {u'comment': [u'kljlk'], u'res_id': [u'4']}>
response_data:[<Comment: 34.kljlk[2014-03-27 06:58:39+00:00]>]
[27/Mar/2014 15:58:39] "POST /withgirl/comment HTTP/1.1" 500 10046
成功将注释数据保存到db表。 为什么会产生500服务器内部错误?
答案 0 :(得分:0)
我认为当您返回HttpResponse时会发生错误。我使用的是django 1.6,您可以与我下面的代码进行比较
return HttpResponse(
json.dumps(result, default=date_handler, sort_keys=True),
"application/json"
)
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj