【问题标题】:ajax not activating, taking me to a different pageajax 没有激活,带我到另一个页面
【发布时间】:2019-10-24 07:53:32
【问题描述】:

代码可以按我的意愿运行,但它会将我带到另一个页面并显示类似 {"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 的 url 是 http://127.0.0.1:8000/community/vote/ 使用 ajax 的 url 是 /社区/发布/3/投票/ 但它说 Not Found: on terminal

【问题讨论】:

    标签: javascript python ajax django


    【解决方案1】:

    您可能会收到未定义 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 似乎缺少结束 &lt;/li&gt; 标记。

    【讨论】:

      【解决方案2】:
          <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
      
      }
      
      
      })
      

      添加到 urls.py

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

      然后添加到视图中。

      def vote2(request):
          if request.method == 'POST':
              response_json = request.POST
              response_json = json.dumps(response_json)
              data = json.loads(response_json)
              this_is_the_pk = data['query']
              this_is_the_comment = data['comment']
              this_is_the_comment2 = data['comment2']
      return JsonResponse(safe=false)
      

      【讨论】:

        【解决方案3】:
         return self.create_response(ret, True) 
        

        应该是

        return JsonResponse(safe=False, ret)
        

        对不起,我没有花时间,懒洋洋地回答。不要改变反应。保持原样,然后做我上面刚刚做的事情。

        应该可以。

        【讨论】:

        • 它会转到另一个页面 /vote 以及消息 "{\"success\": 1, \"voteobj\": 64}"
        • 那是因为你没有用 ajax 调用它。你必须使用 ajax。
        • 那么 ajax 出了什么问题? (就像我在原始问题中发布的那样)请帮助
        • 好吧,你没有使用它。您必须上 youtube 并花时间学习它。使用 Django 时很重要。
        • hmmm 仍然无法正常工作,如果有帮助,我会发布 URL 并在问题中添加赏金
        猜你喜欢
        • 1970-01-01
        • 2019-09-01
        • 2017-09-28
        • 2017-01-02
        • 2017-11-23
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多