javascript - Django在使用ajax时不呈现数据
问题描述
我的 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) // 这是一个 HTML,不是我的数据
您正在获取 HTML,因为您正在呈现整个模板。
我想你只是想回来results
。在这种情况下,只需更改:
return render(request, 'template.html', context={
'results': finalresults,
})
至:
from django.http import JsonResponse
...
...
return JsonResponse(
{'results': finalresults},
)
推荐阅读
- node.js - 无法从后端 mongodb 调用 API
- react-native - 无法在反应原生裸博览会工作流程中使用插页式广告
- java - 使用 JPA 查询方法来搜索特定日期(日和月)的记录
- ios - Core Text 使用 Swift 在 iOS 中计算字母和 ruby 注释帧
- c++ - 尝试集成外部包时生成错误
- mongodb - 无法在 ubuntu 上下载旧版本的 mongo DB
- javascript - 如何在行单击时使用 jquery 获取表单元格值并将值显示到另一个表?
- java - Java Stream按条件减少多个列表
- python - 在我的计算器中,我如何让它只求解一次方程,并在计算器被清除之前阻止用户输入?
- vega-lite - Vega 图表交互式交叉过滤器在第一次点击时填充其他图表