combining django with ajax -- change a table entry without refreshing the whole page
目前,我有一个巨大的表格来显示查询结果。我根据条目的"类型"显示条目的背景颜色。如果用户愿意,我还为用户添加了两个链接以更改条目的类型。
下面非常简单的模板代码。您可以看到用户可以通过访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <table> {% for entry in entries %} {% if entry.type == 1 %} <tr bgcolor= '#007f7f'> {% elif entry.type == -1 %} <tr bgcolor= '#f5cbe1'> {% endif %} <td width="90 pixels">{{ entry.field1 }}</td> <td width="60 pixels">{{ entry.field2 }}</td> <td> newtype1 newtype2 delete <td> </table> |
烦人的问题是,当类型改变时,浏览器必须刷新整个页面以反映背景颜色的变化。
我想将其与 ajax 结合起来,这样无需刷新整个页面即可反映更改。
听说dajax是django和ajax结合最好的框架之一。我想知道如何在 dajax 中实现这一点?我对ajax的经验很少(而且我也认为django比ajax更容易维护),所以我想尽量少写ajax...
谢谢!
我不了解 dajax,但以下是如何使用 jquery 执行此操作的示例。您不需要更改 django 视图(尽管您可能应该这样做)。在对表进行更改之前,ajax 会从 django 视图中检查 http 200。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $('document').ready(function() { $('td a').click(function(e) { e.preventDefault() var href = $(this).attr('href'); var tableRow = $(this).parents('tr'); var action = $(this).html(); $.ajax({ url: href, success: function() { if (action == 'newtype1') { tableRow.attr('bgcolor', '#007f7f'); } else if (action == 'newtype2') { tableRow.attr('bgcolor', '#f5cbe1'); } else if (action == 'delete') { tableRow.remove(); }, )}; } } |
您可以将此代码添加到页面的