Python 无法从Django视图接收到模板的json响应?
我试图将一个json响应从django视图发送到模板,但当我尝试在ajax中console.log响应时,我什么也得不到。我可能做错了什么?我试图将结果数据从视图传递到ajax成功函数。我还注意到一些奇怪的事情,当我在ajax中提到datatype=json时,我在success函数中没有收到任何响应,但当我删除datatype=json时,我在success函数中得到了模板的整个html作为响应。这是为什么Python 无法从Django视图接收到模板的json响应?,python,jquery,json,django,Python,Jquery,Json,Django,我试图将一个json响应从django视图发送到模板,但当我尝试在ajax中console.log响应时,我什么也得不到。我可能做错了什么?我试图将结果数据从视图传递到ajax成功函数。我还注意到一些奇怪的事情,当我在ajax中提到datatype=json时,我在success函数中没有收到任何响应,但当我删除datatype=json时,我在success函数中得到了模板的整个html作为响应。这是为什么 views.py class ChangePassword(View):
views.py
class ChangePassword(View):
def post(self, request, *args, **kwargs):
form = PasswordChangeForm(request.POST)
#current_password = json.loads(get_value.current_password)
#print ('current password',get_value['current_password'])
if form.is_valid():
print("valid form")
user = CustomUser.objects.get(email=request.user.email)
current_password = form.cleaned_data['current_password']
print('current_password',current_password)
new_password = form.cleaned_data['new_password']
print('newpassword',new_password)
if user.check_password(current_password):
print('entered')
update_session_auth_hash(self.request, self.request.user) # Important!
user.set_password(new_password)
user.save()
result = {'success': "Succefully reset your password"};
result = json.dumps(result)
print ('result',result)
return render(request, 'change_password.html',context={'result': result})
else:
return render(request, 'change_password.html', {'error': "We were unable to match you old password"
" with the one we have. <br>"
"Please ensure you are entering your correct password"
"then try again."})
else:
print("not valid")
return render(request, 'change_password.html', {'form':form})
def get(self, request, *args, **kwargs):
return render(request, 'change_password.html', {})
template
function changePassword() {
csrfSetUP()
new_pass = document.getElementById('new_pass')
cur_pass = document.getElementById('current_pass')
if (validpassword(new_pass) && cur_pass!= "") {
var cpass = $('#current_password').val();
var npass = $('#new_pass').val();
var data = {current_password:cpass,new_password:npass}
$.ajax({
url: '/account/change_password/',
type: 'post',
data: data,
dataType: "json",
success: function(json) {
console.log(json)
}
});
} else {
$('#change_password').submit()
}
}
使用AJAX时,必须使用JSONResponse而不是渲染 如果您需要使用JSON生成一些HTML,那么最好使用render_to_string并将HTML字符串返回到AJAX,smth如下所示: html=render_to_string'ajax/product_details.html',{most_visted:most_visted_prods} 返回HttpResponsehtml 注意:当使用render_to_string时,请记住从AJAX中删除dataType:json,因为返回的不是json,而是字符串。 下面有很多这样的例子,但是看看新的例子
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})