【问题标题】:Unable to receive json response from Django view to template?无法从 Django 视图接收到模板的 json 响应?
【发布时间】:2018-10-20 15:04:30
【问题描述】:

我正在尝试将 json 响应从 django 视图发送到模板,但是当我尝试在我的 ajax 中控制台.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()
            }

        }

【问题讨论】:

    标签: python jquery json django


    【解决方案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 下有很多如何做到这一点的示例,但请查看较新的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多