我的 template.html 中有一个简单的代码:
<div>
<input type="button" id="buttonId" value="Show Data">
</div>
<script>
$('#buttonId').click(function() {
$.ajax({
method: 'POST',
data: {
csrfmiddlewaretoken: csrf_token,
click: true
},
success: function(response){
console.log(response) // it is a HTML, not my data
}
});
});
</script>
{{results}}
在我的views.py中:
if request.POST.get('click', False):
... #here I get finalresults
return render(request, 'template.html', context={
'results': finalresults
})
当我按下按钮时,脚本就会运行。所以我知道按下按钮后,finalresults 有内容,但该内容没有到达 HTML 模板。
我做错了什么?
最佳答案
console.log(response) // it is a HTML, not my data
您正在获取 HTML,因为您正在渲染整个模板。
我认为您只想返回结果
。在这种情况下,只需更改:
return render(request, 'template.html', context={
'results': finalresults,
})
致:
from django.http import JsonResponse
...
...
return JsonResponse(
{'results': finalresults},
)
关于javascript - 使用ajax时Django不渲染数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875703/