ajax - Django - ajax 轮询结果在同一页面上
问题描述
我正在学习 django,我的应用程序需要帮助。在一个页面中,我有一个民意调查:我希望在用户投票后,民意调查表单消失,并出现一个 div #ajaxresults,其中包含每个选项的更新投票。我正在使用 ajax 调用,但无法返回更新后的投票。
如果我直接调用'/polls/4/results',我可以看到正确的列表,但我不能在表单的同一页面上包含该块。我错过了什么?
网址.py
app_name = 'polls'
urlpatterns = [
path('', views.index, name='list'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
视图.py
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
#return render(request, 'polls/results.html', {'question': question})
return redirect(question.get_absolute_url())
@require_POST
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
selected_choice = question.choice_set.get(pk=request.POST['selectionId'])
selected_choice.votes += 1
selected_choice.save()
return redirect('polls:results', question_id = question_id)
详细模板(扩展 base.html)
<form id="quiz-module" action="#">
<input type="hidden" id="pollId" name="pollId" value="{{question.id}}">
{% csrf_token %}
<fieldset>
<h2>{{ question.question_text }}</h2>
<ul>
{% for choice in question.choice_set.all %}
<li><input type="radio" name="opt" value="{{ choice.id }}" {% if forloop.first %}required {%endif%}/>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</fieldset>
</form>
<section id="quiz-results">
<h3>Your vote</h3>
<p id="ajaxresults"></p>
<h3>All votes</h3>
<dl>
{%block updated_results %}{% endblock %}
</dl>
</section>
模板投票为空
模板结果(不扩展)
{%block updated_results %}
{% for choice in question.choice_set.all %}
<dt>{{ choice.choice_text }}: </dt><dd id="choiceId-{{ choice.id }}">{{ choice.votes }}</dd>
{% endfor %}
{% endblock %}
js
var args = {
type:"POST",
url:"/polls/"+pollId+"/vote/",
data:data,
success: function( data ) {
//print your vote
results.children('#ajaxresults').html(selectionText);
form.hide('fast');
results.show('fast');
},
error: function(xhr, status, error) {
alert(error+'<br/>'+"Sorry. Can't submit your vote. Please, reload the page and try again")
},
};
$.ajax(args);
解决方案
推荐阅读
- python - 如何使用 python 或 Scala 将复杂的 SQL 查询转换为 spark-dataframe
- email - 从 HTTP 切换到 SSL 后私有域电子邮件被标记为垃圾邮件
- logging - 如何控制 podman 容器日志行为 (ctr.log)
- java - Java:布尔+整数
- flutter - 使用 IconData CodePoint 不显示颤振仪表图标
- python - 使用 MPI (SLURM) 运行 Python 代码比作为单个进程运行需要更长的时间
- javascript - React Hook - 只听窗口 *width* 大小变化
- c# - 如何转换为驻留在外部程序集中的具体类型
- php - 如何使用php跳过数据库中的表
- r - R中的Vlookup,在不匹配的地方保留一个空单元格