javascript 刷新由 django 模板生成的 <div> 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3583534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh <div> element generated by a django template
提问by Jonathan
How do I refresh a certain element within a django template?
Example:
如何刷新 django 模板中的某个元素?
例子:
{% if object.some_m2m_field.all %}
<h3>The stuff I want to refresh is below</h3>
<div id="the-div-that-should-be-refreshed">
{% for other_object in object.some_m2m_field.all %}
<a href="www.example.com">{{ other_object.title }}</a>
{% endfor %}
</div>
{% endif %}
Lets say some other element in the page triggers a javascript that should refresh the div above. Is there a way to cause django to refresh this specific element within the template?
假设页面中的其他一些元素触发了一个 javascript,它应该刷新上面的 div。有没有办法让 django 刷新模板中的这个特定元素?
If not, I'll have to monkey-patch the div using regular JS or jQuery methods and not use the great power of django's template layer. Also, the above code is a simplification of the actual template, I use much of the template's power, so monkey-patching the resulting html will be a nightmare...
如果没有,我将不得不使用常规 JS 或 jQuery 方法对 div 进行猴子修补,而不是使用 django 模板层的强大功能。此外,上面的代码是对实际模板的简化,我使用了模板的大部分功能,因此对生成的 html 进行猴子修补将是一场噩梦......
回答by o.elias
You could use an async request to fill the div element. The async request is answered by django using the template engine.
您可以使用异步请求来填充 div 元素。django 使用模板引擎响应异步请求。
In this case you would have to outsource the template code of the div element into a seperate template file.
在这种情况下,您必须将 div 元素的模板代码外包到一个单独的模板文件中。
UPDATED WITH EXAMPLE:
更新示例:
Javascript:
For refreshing the view asynchronously, use JQuery for example:
Javascript:
为了异步刷新视图,例如使用 JQuery:
$.ajax({
url: '{% url myview %}',
success: function(data) {
$('#the-div-that-should-be-refreshed').html(data);
}
});
Async View:
异步视图:
def myview(request):
object = ...
return render_to_response('my_template.html', { 'object': object })
Template:
模板:
{% for other_object in object.some_m2m_field.all %}
<a href="www.example.com">{{ other_object.title }}</a>
{% endfor %}
Best regards!
最好的祝福!
回答by Bernhard Vallant
You can have a look at eg. this Ajax with Django tutorial. Anyways as mentioned above you can always use django's template engine, no matter if the view is called in a normal or an ajax request! If you have to use ajax with django more frequently it makes sense to have a look at something like dajax, which is an ajax library for django (have a look at the tutorials there).
你可以看看例如。这个Ajax with Django 教程。无论如何,如上所述,您始终可以使用 django 的模板引擎,无论视图是在普通请求还是 ajax 请求中调用!如果您必须更频繁地将 ajax 与 django 一起使用,那么查看dajax 之类的东西是有意义的,它是 django 的 ajax 库(查看那里的教程)。

