javascript - Django、Ajax 和 jQuery - 无需重新加载页面并为用户打印“成功”消息即可发布表单
问题描述
我想请你帮忙。我想创建简单的投票系统。我不知何故成功了。我有一个简单的“UP”按钮,该按钮使用简单的 +1 整数作为帖子的分值。它现在有很多问题,但我以后会和他们斗争。
现在我想在不刷新页面的情况下添加这个 +1 分数(就像大多数现代网站一样)。我做了我的谷歌搜索,我想出了这个:https ://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/我不得不说它工作得很好,即使我对 js、jquery 或阿贾克斯。
我的问题是,javascript正在添加这个+1,但它也给了我一些我无法理解的错误:
responseText: "TypeError at /viewquestion/6/voteup\n__init__() missing 1 required positional argument: 'data'\n\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/viewquestion/6/voteup\nDjango Version: 3.0.4\n
我想摆脱它们或了解它们的性质:P
我的第二个或主要问题是。投票正在进行,但分数不会改变,因为当然,页面没有重新加载。而且我也无法为用户打印“成功投票”消息,因为网站不刷新。
给用户一些简单的信息“投票成功”对我来说就足够了。最好的情况是立即更新分数,但我不知道这会使事情复杂化多少。
你能帮我解决这个问题或指出我正确的方向吗?因为我对 js/ajax 或 jquery 一无所知,所以即使有谷歌搜索的想法,我也很难想出。
这是我现在能够做的:
base.html:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script>
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
视图.py:
@login_required()
def questionvoteup(request, question_pk):
question = get_object_or_404(Question, pk=question_pk, user=request.user)
if request.is_ajax() and request.method == "POST":
question.votesscore += 1
question.amountofvotes += 1
question.save()
messages.success(request, 'Thank you for your vote!')
return JsonResponse()
else:
return HttpResponse(400, 'Invalid form')
主页.html:
<ul>
{% for question in allquestionswithanswers %}
<li>
{{ question }} Score: {{ question.votesscore }} {{ question.user }}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
<br><br>
<form class='my-ajax-form' method='POST' action='.' data-url="{% url 'questionvoteup' question.id %}" >
{% csrf_token %}
<button type='submit'>UP</button>
</form>
{% for answer in question.answer_set.all %}
{{ answer }}<br>
{% endfor %}
</li>
{% endfor %}
</ul>
谢谢你。
解决方案
JsonResponse:第一个参数 data 应该是一个 dict 实例。
您的看法:
def questionvoteup(request, question_pk):
question = get_object_or_404(Question, pk=question_pk, user=request.user)
if request.is_ajax() and request.method == "POST":
question.votesscore += 1
question.amountofvotes += 1
question.save()
data = {
"msg": 'Thank you for your vote!'
}
return JsonResponse(data)
else:
return HttpResponse(400, 'Invalid form')
比在您的模板中:
$(".my-ajax-form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.data('url');
$.post(url).done(function(data) {
alert(data.msg); // get your response data
});
});
推荐阅读
- javascript - 如何在 chrome/safari 上显示多个谷歌地图信息窗口?
- java - 为多个并行流更新一个计数器
- python - 使用python进行多项式加法
- configuration - 弹簧型材。配置数据库问题
- jquery - owl carousel 跳转到特定幻灯片并为其添加类
- javascript - React Native Wix 日历标记日期显示错误
- asp.net - 需要在 MVC 中渲染部分视图以代替具有相同布局的另一个部分视图
- python - 我需要为 python pandas 中的缺失索引插入空值
- node.js - webpack 配置文件中没有定义插件
- reactjs - React-select 在 Laravel-mix 中没有显示价值