【问题标题】:Django, Ajax and jQuery - posting form without reloading page and printing "succes" message for userDjango、Ajax 和 jQuery - 无需重新加载页面并为用户打印“成功”消息即可发布表单
【发布时间】:2020-04-25 21:32:06
【问题描述】:

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

现在我想在不刷新页面的情况下添加这个 +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 一无所知,所以即使有谷歌搜索的想法对我来说也很难。

这是我现在能做的:

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>

views.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')

home.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>

谢谢。

【问题讨论】:

    标签: javascript python jquery django ajax


    【解决方案1】:

    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
    
        });
    
    });
    

    【讨论】:

    • 非常感谢!我认为“数据”是一些我无法找到的值名称。但是“数据”是 js 试图返回的东西,现在它是有道理的。你能告诉我,我怎样才能打印这个返回的“数据”?我尝试使用 {{ data }} 或 {{ msg }} 但没有以这种方式呈现。谷歌搜索“django 如何打印 json 响应”对我来说并不顺利:P
    • @Peksio,我用模板中的一个小例子编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多