刷新使用jQuery和AJAX在Django一个div [英] Refresh a div in Django using JQuery and AJAX

查看:119
本文介绍了刷新使用jQuery和AJAX在Django一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想刷新我与AJAX和JQuery的(在Django)网页的某一部分。我怎样才能得到它重新显示只有DIV,而不是整个页面。

I am trying to refresh a certain part of my page with AJAX and JQuery (in Django). How can I get it to redisplay only the div, rather than the whole page.

    // In my template
    var tag_cloud_floor = function(floor) {
    $.ajax({ url: "/{{ user }}/{{ tag }}/",
                     data: {tag_cloud_floor: floor},
                     type: 'POST',
                     success: function(data) {
                         $('#tag_cloud).html(data);
                     },
    });

};

下面是我的看法。

@login_required
def tag_page(request, username, tag):
  if username == request.user.username:
    tags = request.user.userprofile.tag_set.all()

    if request.is_ajax() and request.POST:
      floored_tags = []
      for t in tags:
        if t.item_set.all().count() >= int(request.POST['tag_cloud_floor']):
          floored_tags.append(t)
      tags = floored_tags

    tag = Tag.objects.get(title=tag)
    items = tag.item_set.all()
    return render_to_response("tag_page.html", { 'user': request.user , 
                                              'tag': tag,
                                             'tags': tags,
                                            'items': items })
  else:
  return HttpResponseRedirect('/' + request.user.username + '/')

目前,它把整个HTML页面到#tag_page股利。我想它来代替旧的#tag_page分区与新的#tag_page股利。如果我更换 $('#tag_cloud)HTML(数据); $(身体)HTML(数据); 它刷新整个页面就应该是这样,但我想刷新整个页面是一种浪费。

Currently, it places the entire html page into the #tag_page div. I want it to replace the old #tag_page div with the new #tag_page div. If I replace $('#tag_cloud').html(data); with $('body').html(data); it refreshes the whole page to how it should be, but I figure refreshing the whole page is a waste.

如果有更好的方法来做到这一点,让我知道。

If there is a better way to do this, let me know.

推荐答案

首先,它看起来像你的code坏了 - 这不是一个有效的JavaScript / jQuery的指令:

First, it looks like your code is broken - this is not a valid Javascript/jQuery instruction:

$('#tag_cloud').html(data);

对于只刷新一个 DIV ,我会提取该div的内容到一个单独的模板 my_div.html ,使用包括它的主要页面模板{%包括my_div.html%} 。然后,在我的AJAX的看法,我会渲染和只返回呈现 my_div.html

As for refreshing only a single div, I would extract contents of that div to a separate template my_div.html, include it in the main page template using {% include "my_div.html" %}. Then, in my AJAX view, I would render and return only that rendered my_div.html.

这篇关于刷新使用jQuery和AJAX在Django一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆