Ajax无法激活,将我带到其他页面

时间:2019-06-09 18:54:39

标签: javascript python ajax django

代码按我的意愿工作,但它带我到另一个页面,并且有类似{“ success”:1,“ voteobj”:57}的内容。我被告知ajax就是为此而设计的,但我并不擅长。这就是我所拥有的。有人可以检查我在哪里出错了,以及应该怎么做才能解决它?

<script type="text/javascript">
    jQuery(document).ready(function($) 
        {
    $(".vote_form").submit(function(e) 
        {
                e.preventDefault(); 
                var btn = $("button", this);
                var l_id = $(".hidden_id", this).val();
                btn.attr('disabled', true);
                $.post("vote/", $(this).serializeArray(),
                function(data) {
                        if(data["voteobj"]) {
                    btn.text("-");
                        }
                        else {
                    btn.text("+");
                        }
                });
                btn.attr('disabled', false);
        });
        });
</script>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>


<form method="post" action="{% url 'vote' %}" class="vote_form">
    <li> [{{ post.votes }}]
        {{post}}
        {% csrf_token %}
        <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
        <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
        {% if not user.is_authenticated %}
        <p>login to vote</p>

        {% elif post.pk not in voted %}
            <button class="btn btn-primary">like</button>
        {% else %}
        <button class="btn btn-primary">dislike</button>
        {% endif %}
            </form>

以下是我的python代码

class JSONFormMixin(object):
    def create_response(self, vdict=dict(), valid_form=True):
        response = HttpResponse(json.dumps(vdict), content_type='application/json')
        response.status = 200 if valid_form else 500
        return response

class VoteFormBaseView(FormView):
    form_class = VoteForm

    def create_response(self, vdict=dict(), valid_form=True):
        response = HttpResponse(json.dumps(vdict))
        response.status = 200 if valid_form else 500
        return response

    def form_valid(self, form):
        post = get_object_or_404(Post, pk=form.data["post"])
        user = self.request.user
        prev_votes = Vote.objects.filter(voter=user, post=post)
        has_voted = (len(prev_votes) > 0)

        ret = {"success": 1}
        if not has_voted:
            # add vote
            v = Vote.objects.create(voter=user, post=post)
            ret["voteobj"] = v.id
        else:
            # delete vote
            prev_votes[0].delete()
            ret["unvoted"] = 1
        return self.create_response(ret, True)


    def form_invalid(self, form):
        ret = {"success": 0, "form_errors": form.errors }
        return self.create_response(ret, False)



urls.py

urlpatterns = [   
    path('vote/', auth(VoteFormView.as_view()), name='vote'),

编辑:我按照以下网络上的说明进行操作:https://arunrocks.com/building-a-hacker-news-clone-in-django-part-4/

一切都很好,但ajax在我这边

编辑:因此,没有ajax的网址是http://127.0.0.1:8000/community/vote/ 使用ajax时,URL为 / community / post / 3 / vote / 但它显示未找到:在终端

3 个答案:

答案 0 :(得分:0)

 return self.create_response(ret, True) 

应该是

return JsonResponse(safe=False, ret)

对不起,我没花时间懒洋洋地回答。不要更改响应。保持它不变,然后执行我上面所做的操作。

应该工作。

答案 1 :(得分:0)

def integer_to_english(number):
    if number>=1 and number<=1000:
        a = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty ','thirty ','fourty ','fifty ','sixty ','seventy ','eighty ','ninty ']
        if number<=20:
            if number%10==0: return a[number]
            else: return a[number]
        elif number<100:
            b=number-20
            r=b%10
            b//=10
            return a[20+b]+a[r]
        elif number<1000:
            if number%100==0:
                b=number//100
                return a[b]+' hundred'
            else:
                r=number%100
                b=number//100
                if r<=20:
                    return a[b]+' hundred'+' and '+a[r]
                else:
                    r=r-20
                    d=r//10
                    r%=10
                    return a[b]+' hundred'+' and '+a[20+d]+a[r]
        elif number==1000:
            return 'one thousand'
        else:
            return -1

number=789
print(integer_to_english(number))

添加到urls.py

    <button class="btn btn-primary" onclick="runthis({{post.pk}})">like</button>

function runthis(n){




var patch = '{% url "vote2" %}'

comment = document.getElementById('id_post').value
comment2 = document.getElementById('id_voter').value
info = {"comment":comment, "comment2":"comment2", 'csrfmiddlewaretoken':"{{ csrf_token }}", 'query':n}


$.ajax({
  type: "POST",
  url: patch,
  data:info,
    datatype:'json',
   headers: { "X-CSRFToken": '{{csrf_token}}' },



success: function(data){

console.log('success')
return

}


})

然后添加到视图。

urlpatterns = [   
    path('vote/', auth(VoteFormView.as_view()), name='vote'),
    path('vote2/', view.vote2, name='vote2')]

答案 2 :(得分:0)

您可能会收到未定义JQuery的错误,因此e.preventDefaults()永远不会运行,并且您会收到标准的表单提交操作。尝试在此脚本之前包含用于拉入JQuery的脚本标签。这可能是这样的:

<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
<script type="text/javascript">
    jQuery(document).ready(function($) 
        {
    $(".vote_form").submit(function(e) 
        {
                e.preventDefault(); 
                var btn = $("button", this);
                var l_id = $(".hidden_id", this).val();
                btn.attr('disabled', true);
                $.post("vote/", $(this).serializeArray(),
                function(data) {
                        if(data["voteobj"]) {
                    btn.text("-");
                        }
                        else {
                    btn.text("+");
                        }
                });
                btn.attr('disabled', false);
        });
        });
</script>


<form method="post" action="{% url 'vote' %}" class="vote_form">
    <li> [{{ post.votes }}]
        {{post}}
        {% csrf_token %}
        <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
        <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
        {% if not user.is_authenticated %}
        <p>login to vote</p>

        {% elif post.pk not in voted %}
            <button class="btn btn-primary">like</button>
        {% else %}
        <button class="btn btn-primary">dislike</button>
        {% endif %}
            </form>

此外,您的HTML似乎缺少结束符</li>