Django与Ajax和jQuery

时间:2012-10-08 14:39:04

标签: ajax django

我希望点击其中一个Item显示一个带有描述的窗口(单项描述)。

如何使用Djaxo使用Ajax和jQuery创建它?

模型:

class Item(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    desc = models.TextField()

的观点:

def item_list(request):
    items = Item.objects.all()[:6]
    return render_to_response('items.html', {'items':items}, context_instance=RequestContext(request))


def single_item(request, slug):
    item = Item.objects.get(slug=slug)
    return render_to_response('single.html', {'item':item}, context_instance=RequestContext(request))

模板:

<!-- Single item description: -->

<div id="description">
    <img src="/site_media/images/photo.png">
        <div id="item_description">
            <input name="add" type="button" id="add" value="Add to Cart">
                <p class="title">Single Item name</p>
                <p class="description"><span>Description:</span>
                    This is single item description
                </p>
            </div>
        </div>

<!-- All item: -->

            <div id="item">
                {% for i in items %}
                    <div class="item">
                    <img src="/{{ i.image.url }}"  />
                    <p>
                    <span> {{ i.name }} </span>
                    <span> {{i.price}} </span>
                    </p>
                    </div>
                {% endfor %}
            </div>
        </div>

    </div>

1 个答案:

答案 0 :(得分:2)

如果您想使用ajax刷新页面,则需要做三件事:

  • 在urls.py中为ajax调用添加一个条目(或者在视图函数中添加一个条件来处理请求,如果它是ajax)
  • 添加javascript块以进行ajax调用并使用新数据更新html / text
  • 在views.py中添加代码以处理ajax调用并使用json数据进行响应

<强> urls.py ...

url(r'/ajax-view-single/)/$', 'ajax_single_item', name='app_name_ajax_single_item'),

<强> HTML / JS

<script type="text/javascript" src="/js/json2.js"></script>
$("#view-single-item").click(function () {
        try {
            // get slug from html
            var slug = "";
            var data = {
                slug: slug
            };
            $.get('{% url app_name_ajax_single_item %}', data, function(data){

               // your data returned from django is in data
               alert(data.item_name);

            }, 'json');
            //$('#error').hide();
        }
        catch(err) {
            $('#error').html(err);
            $('#error').show();
        }
        return false;
    });

<强> views.py

from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import get_object_or_404

def ajax_single_item(request):
    '''gets single item'''
    if not request.is_ajax():
        return HttpResponse(simplejson.dumps({'result': False}))

    # get slug from data
    slug = request.GET.get('slug', None)

    # get item from slug
    item = get_object_or_404(Item, slug=slug)
    return HttpResponse(simplejson.dumps({
        'result': True,
        'item_name': item.name,
        'item_price': item.price,
        'item_desc': item.desc,
        'item_slug': item.slug
    }))