[英]Django returns invalid ajax response
I have a ajax call in my django template file as: 我在我的django模板文件中有一个ajax调用:
$(document).ready(function () {
$("button#wdsubmit").click(function(){
$.ajax({
type: "post",
url: "/audit/addwd/",
data: $('form.wddetails').serialize(),
dataType: "json",
success: function(msg){
alert(msg);
alert('Added Successfully');
$("#newwd").modal('hide'); //hide popup
},
error: function(msg){
alert(msg.success);
}
});
});
});
Form: 形成:
class WDForm(ModelForm):
class Meta:
model = WDModel
fields = '__all__'
and view in django is : 并在django中查看:
def addwd(request):
if request.method == 'POST':
updated_request = request.POST.copy()
updated_request.update({'updated_by': request.user.username})
form = WDForm(updated_request)
if form.is_valid():
form.save()
response = simplejson.dumps({'success': True})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
else:
response = simplejson.dumps({'error': True})
return HttpResponse(response , content_type="application/json")
Whenever I make a Ajax call it always returns error even though I have sent Success(Means the form is valid and data is successfully pushed to database). 每当我进行Ajax调用时,它总是返回错误,即使我已经发送了Success(表示表单有效并且数据已成功推送到数据库)。
I also tried to send response={'success':True} doesn't work. 我也尝试发送response = {'success':True}不起作用。
Please help me to solve this issue. 请帮我解决这个问题。
Environment Details: Python verion: 3.4 Django :1.7 Windows OS 8 环境细节:Python版本:3.4 Django:1.7 Windows OS 8
I doubt on this line " response = simplejson.dumps({'success': success})
" 我怀疑这一行“ response = simplejson.dumps({'success': success})
”
you can try JsonResponse objects. 你可以尝试JsonResponse对象。
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.