Django返回渲染模板和Json响应

时间:2017-05-12 18:34:22

标签: python json ajax django render

我如何在 Django 中渲染模板,并在一次返回中制作 JsonResponse

return render(request, 'exam_partial_comment.html', {'comments': comments, 'exam_id': exam})

我尝试使用JsonResponse或类似的内容对此进行整理,以便呈现 exam_partial_comment.html 并返回

JsonResponse({"message": message})

所以我可以用ajax成功功能显示消息:

console.log(data.message)

1 个答案:

答案 0 :(得分:1)

正如@nik_m所提到的那样。你不能在你的回复中发送html和json。另外,鉴于事实,Ajax调用了无法渲染模板。虽然,你可以做这样的事情来实现你想要的东西

在views.py

def view_name(request):
    if request.method == 'POST':
        html = '<div>Hello World</div>'
        return JsonResponse({"data": html, "message": "your message"})

在html中

<div id="test"></div>
<script>
$(document).ready(function(){
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/view/',
        data: data,
        success: function(response) {
             console.log(response.message);
             $('#test').append(response.data);
       }
    });
});
</script>

希望这有帮助。