【问题标题】:Django return render template and Json responseDjango 返回渲染模板和 Json 响应
【发布时间】:2017-10-12 04:04:53
【问题描述】:

我如何在 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)

【问题讨论】:

  • 您确实意识到来自服务器的每个响应都有特定的内容类型,对吧?你想回报什么? JSON 还是 HTML?

标签: python json ajax django render


【解决方案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>

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多