【问题标题】:How to apply ajax call to all model objects in DJANGO如何将 ajax 调用应用于 DJANGO 中的所有模型对象
【发布时间】:2015-07-22 07:23:23
【问题描述】:

我需要实现 AJAX 并且它工作正常。但是,我在将 ajax 应用于模型的每个实例时遇到问题。它只是应用于顶部对象并在同一页面上应用 ajax 调用。对于剩余的对象,当我单击链接时,它会将我定向到新页面并向我显示我不想要的 JSON 对象。

Views.py

def upvote(request, post_id):

if request.method == "POST":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    return JsonResponse({'count':p.upvote })

if request.method == "GET":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    data = {
        'count' : p.upvote,
    }
    return JsonResponse({'count': p.upvote})

网址.py

url(r'^(?P<post_id>[0-9]+)/upvote/$', views.upvote, name='upvote-detail'),

Views.html

<script>
    $(function(){
       $('#up_vote').click(function(e) {
          e.preventDefault();
          window.alert("hello");
          console.log("hello");


          $.ajax({
            url: $(this).attr('href'),
            type :'get' ,
            success : function (data){
              // alert('success');
              $('#upvote_count').html(data.count);
            },
            failure : function (data){
              alert('failure') ; 
            }
          }) ;  // ajax call 

       }); // upvote link call
</script>

<div id="columns">
    {% for post in object_list %}

        <div class="pin">
            <a href="/posts/{{ post.id }}/">

            <img src= "/static/media/{{post.image}}" />
            </a>
            <p>
                {{post.description}}
                (<a href="{% url "post-edit" pk=post.id %}">edit</a>)
            </p>


            <div style="float:left">
              <a href='{% url 'upvote-detail' post.id %}' id='up_vote'>Up vote  </a>
              <span id='upvote_count'> {{ post.upvote }} </span> 
            </div>


            <div style="float:right">
              <a href='{% url 'downvote-detail' post.id %}' id='down_vote'> Down vote </a>
              <span id='downvote_count'>{{post.downvote}}</span>
            </div>


        </div>
    {% endfor %}

    </div>

这是我所有的文件。目前 AJAX 调用运行良好。它只是应用于 LOOP 中对象的顶部(第一个)。对于剩余对象,当我单击链接时,它会将我呈现到新页面。有人可以识别问题吗? 谢谢,

【问题讨论】:

  • 基本上返回一个JsonResponse,关于如何实现ajax的完整答案对于堆栈溢出来说过于宽泛,它已经在文档中显示了
  • @Sayse 你能告诉我在哪里可以找到文档吗?或任何有用的链接
  • 我花了大约 15 秒才找到the answer on SO。请在询问之前做一些研究。

标签: jquery python ajax django django-views


【解决方案1】:

在views.py中

def detail(request):
    return render(request, 'detail.html', {'posts': Post.objects.all()})

def upvote(request, post_id):
   if request.method == "POST":
       p = get_object_or_404(Post, pk=post_id)
       p.upvote += 1
       p.save()
       return JsonResponse({'count':p.upvote })
   return JsonResponse({})

详细.html:

{% for post in posts %}
     <a href='{% url 'upvote-detail' post.id %}' id='up_voite'>Up voite <span id='voite_count'> {{ post.upvote }} </span> </a>
 {% endfor %}

<script>
    $(function(){
       $('#up_voite').click(function(e) {
          e.preventDefault();
          $.post($(this).attr('href'), function(data) {
              $(this).find('span').html(data.upvote);
          });
       });
    });
</script>

代码未检查

【讨论】:

  • 这很好,只是你真的不应该在 GET 上执行 db-modifying 操作。不妨让 JS 做一个 POST 并在 upvote 函数中检查它。
  • @comalex3 谢谢。由于某种原因,它没有更新投票数据。相反 {{ post.upvote }} 保持不变。 标签确实显示了链接,但它没有更新赞成票,也没有显示在 span 标签上。
  • @user3487775 调试你的代码,调试 javascript 使用 console.log(),alert() 或你的浏览器调试工具栏,调试 python 代码使用 print() 或 pdb (ipdb),看到返回一个发布请求......你会明白为什么代码不起作用
  • @comalex3 感谢您的帮助。它显示 json 响应,但不是在同一页面上更新,而是将我重定向到新页面并在新页面上显示 json 响应。
  • @user3487775 您可能在 javascript 中有错误,或者忘记了 e.preventDefault();
【解决方案2】:

试试这个:

def upvote(request, post_id):
    p = get_object_or_404(Post, pk=post_id)
    errors = []
    data = {}
    try:
        p.upvote += 1
        p.save()
        data = {
            'success': 1,
        }
    except:
        errors.append(['There was an error'])
        data = {
            'success': 0,
            'errors':errors,
        }
    return HttpResponse(json.dumps(data))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 2022-10-01
    • 2015-03-13
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多