首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django、Ajax和jQuery -发布表单,无需重新加载页面和打印“成功”消息供用户使用。

Django、Ajax和jQuery -发布表单,无需重新加载页面和打印“成功”消息供用户使用。
EN

Stack Overflow用户
提问于 2020-04-25 21:32:06
回答 1查看 64关注 0票数 1

我想请你帮忙。我想建立一个简单的投票制度。我不知怎么成功了。我有一个简单的“向上”按钮,这个按钮用简单+1整数表示post的积分值。它现在有很多问题,但我稍后会与他们斗争。

现在,我想在没有刷新页面的情况下添加这个+1分数(就像大多数现代网站一样)。我做了我的googling,我想出了这样的结论:https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ --我不得不说它运行得很好,即使我对js、jquery或ajax一无所知。

我的问题是,javascript添加了这个+1,但它也给我带来了一些我无法理解的错误:

代码语言:javascript
复制
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

我想要么摆脱它们,要么理解它们的本质。

我的第二个或主要的问题是。投票是有效的,但分数不会改变,因为当然,页面没有重新加载。而且我也不能为用户打印“成功投票”的信息,因为,好网站并不新鲜。

给用户一些简单的信息“投票成功”对我来说就足够了。最好的情况是立即更新分数,但我不知道这会使事情变得复杂多少。

你能帮我一下还是指给我正确的方向?因为我对js/ajax或jquery一无所知,所以我甚至很难找到谷歌搜索的想法。

以下是我现在能做的事情:

base.html:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
<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>

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-25 22:15:10

JsonResponse:第一个参数,数据,应该是一个dict实例。

你的观点:

代码语言:javascript
复制
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')

而不是你的模板:

代码语言:javascript
复制
$(".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

    });

});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61432895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档