【问题标题】:How can I have Django generate or change a DOM element?如何让 Django 生成或更改 DOM 元素?
【发布时间】:2018-01-20 13:16:23
【问题描述】:

我正在构建一个 Django 应用程序,我希望有一个视图/函数在每次运行时将一行 html 添加到具有 id 的特定 div 元素的内部 html。

我知道如何使用 Javascript 来执行此操作,但是每次运行时我都需要视图来运行该脚本。 有没有办法在 Python 文档中做到这一点?

【问题讨论】:

  • 您可以对运行该脚本的特定 url 使用 ajax requets

标签: python django dom backend dynamic-content


【解决方案1】:

你的问题的标题是关于在 python 中创建一个 DOM 元素。为了做到这一点,在你的views.py中

from django.template import Context, Template

def in_some_view(request):
    template = Template('<div class="new-dom-element">Element</div>')
    '''
    You can create elements above. You can even give it Context Variables
    For example: template = Template('<div class="new-dom-element">{{ context_variable }}</div>')
    '''
    context = Context({'context_variable': your_python_variable})
    #By sending the context variable "your_python_variable", you can do anything iteratively.

    dom_element = template.render(context) 
    #Now you can return this dom_element as an HttpResponse to your Javascript.
    #Rest of your code.
    return HttpResponse(dom_element)

注意:我在回答这个问题时谨记您不想采取AJAX 请求域之外的方式。如果是这样,那么如果 HTML 已经显示在浏览器屏幕上,那么很难带来和附加一些数据。这正是最初创建 AJAX 的原因。

希望这会有所帮助。谢谢。

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2011-02-11
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多