Как я сейчас делаю Ajax с Django: ищу советы / комментарии - PullRequest
3 голосов
/ 07 ноября 2010

Я хотел бы поделиться с вами тем, как я сейчас работаю над Ajax с Django.Я хотел бы получить ваши советы / комментарии, чтобы увидеть, правильно ли я это делаю.

Я, конечно, упрощу код, просто чтобы показать процесс.

Вот мой код шаблона:

<!-- I store the full url to access object details so I can use url feature.
If I just store the pk, I would have to hardcode the url to fetch the object
detail later. Isn't it? -->
<ul>
{% for item in items %}
    <li url="{% url project.item.views.details item.pk %}">{{ item.name }}</li>
{% endfor %}
<ul>

<div id="details"></div>


<script> 
$("li").click(function(elmt){
    // I just reuse the url attribute from the element clicked
    var url = $(elmt.currentTarget).attr('url');
    $.getJSON(url, function(data) {
        if (data.success) {
            $("#details").html(data.html);
        } else {
            $("#details").html("Something went wrong");
        }
    });
});
</script>

Вот код, который я использую на мой взгляд:

def details(request, item_id):
    item = Items.objects.get(pk=item_id)
    # Just render a view with the details, and return the view
    html = render_to_string("items/_details.html", {'item': item})
    return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")

Что вы думаете о моем способе сделать это?

Заранее спасибо за вашепомощь!

Ответы [ 2 ]

2 голосов
/ 07 ноября 2010

Ничего плохого в коде Django, но вы можете захотеть, чтобы он работал и для клиентов, не поддерживающих JavaScript, и использовать действительный HTML:

<ul>
{% for item in items %}
    <li><a href="{{ item.get_absolute_url }}">{{ item.name }}</a></li>
{% endfor %}
<ul>

$("a").click(function(){
    // I just reuse the url attribute from the element clicked
    // li does not have an url attribute
    var url = $(this).attr('href');
    $.getJSON(url, function(data) {
        if (data.success) {
            $("#details").html(data.html);
        } else {
            $("#details").html("Something went wrong");
        }
    });
    return false;
});

def details(request, item_id):
    item = Items.objects.get(pk=item_id)
    # Just render a view with the details, and return the view
    if request.is_ajax():
        html = render_to_string("items/_details.html", {'item': item})
        return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
    else:
        #non ajax request rendering complete html
        return render_to_response("items/detail.html", {'item': item})
0 голосов
/ 07 ноября 2010

Лично я предпочитаю использовать промежуточное ПО для размещения веб-сервисов, поскольку они позволяют вам не загружать Django полностью, но по-прежнему иметь доступ к тому, что вам нужно.

Тем не менее, использование представлений для веб-сервисов, безусловно, допустимо и работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...