我想和你分享一下我是如何用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}$你觉得我的方法怎么样?在
提前感谢您的帮助!在
Django代码没有任何问题,但您可能希望它也适用于非javascript客户端并使用有效的HTML:
我个人更喜欢使用中间件来托管web服务,因为它们允许您不完整地加载Django,但是仍然可以访问您需要的内容。在
不过,对web服务使用视图肯定是有效的,而且是有效的。在
相关问题 更多 >
编程相关推荐