繁体   English   中英

Django、Ajax 和 jQuery - 无需重新加载页面并为用户打印“成功”消息即可发布表单

[英]Django, Ajax and jQuery - posting form without reloading page and printing “succes” message for user

我想请你帮忙。 我想创建简单的投票系统。 我不知何故成功了。 我有一个简单的“UP”按钮,该按钮使用简单的 +1 integer 来发布帖子的得分值。 它现在有很多问题,但我以后会和他们斗争。

现在我想在不刷新页面的情况下添加这个 +1 分数(就像大多数现代网站一样)。 我做了我的谷歌搜索,我想出了这个: https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/我不得不说它工作得很好,即使我对 js 的了解为零,jquery 或ajax。

我的问题是,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 一无所知,因此即使有谷歌搜索的想法,我也很难想出。

这是我现在能够做的:

基地.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

    });

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM