无法接收从Django视图到模板的json响应?

时间:2018-05-10 10:53:54

标签: python jquery json django

我正在尝试将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()
            }

        }

1 个答案:

答案 0 :(得分:1)

当您使用AJAX时,您必须use JSONResponse()而不是render()

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

如果您需要使用该JSON生成一些HTML - 最好使用render_to_string method并将一个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,而是返回字符串。

附:在this question下,有很多例子可以说明如何做到这一点,但请看一下新的。

相关问题