我现在如何使用Django使用Ajax:寻求建议/评论

2024-04-23 17:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想和你分享一下我是如何用Django来做Ajax的。我想听听你的建议/意见,看看我是否做得对。在

我当然会把代码简单化,只是为了展示这个过程。在

以下是我的模板代码:

<!-- 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>

以下是我在我看来使用的代码:

^{pr2}$

你觉得我的方法怎么样?在

提前感谢您的帮助!在


Tags: thetostore代码divurldataobject
2条回答

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})

我个人更喜欢使用中间件来托管web服务,因为它们允许您不完整地加载Django,但是仍然可以访问您需要的内容。在

不过,对web服务使用视图肯定是有效的,而且是有效的。在

相关问题 更多 >