[英]Unable to receive json response from Django view to template?
我正在嘗試從django視圖向模板發送json響應,但是當我嘗試在我的ajax中console.log響應時,我什么也沒得到。 我可能做錯了什么? 我試圖將結果數據從視圖傳遞到我的Ajax成功函數。 我還注意到一些奇怪的事情,當我在ajax中提到datatype = json時,我在成功函數中未收到任何響應,但是當我刪除dataType = json時,我在我的成功函數中獲得了模板的整個html作為響應。 這是為什么 ??
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()
而不是render()
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
如果您需要使用該JSON生成一些HTML,則最好使用render_to_string
方法並將html字符串返回到AJAX中,如下所示:
html = render_to_string('ajax/product_details.html', {"most_visited": most_visited_prods}) return HttpResponse(html)
注意:使用render_to_string
請記住從AJAX中刪除dataType: "json"
,因為返回的不是JSON,而是一個字符串。
PS在這個問題下 ,有很多例子可以做到這一點,但請看一下更新的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.