我怎么能在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)
正如@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>
希望这可以帮助。