Django 返回渲染模板和 Json 响应



如何在 Django 中渲染模板并在一次返回中做出 Json响应

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)

正如@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>

希望这有帮助。

最新更新