javascript脚本块未在django模板中呈现

时间:2012-05-07 19:15:47

标签: jquery ajax django

我正试图通过“current.html”

从ajax中取出

处理表单的视图呈现“form.html”

“current.html”类似于:

<script>
    // ajax that pulls the form on a#get_form click 
    // fills up div#mod_post with the result 
</script>

<a id="get_form" href="{% url to the view that handles the form %}">get form</a>

<div id="mod_post" style="display:none;">
    {% include "form.html" %}
</div>

直到这里都很好...表格很好地检索并显示。

“form.html”类似于:

<script type="text/javascript" src="/the/script/that/should/handle/the/post.js"></script>

<form id="mod_form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
    <table class="form">
        {{ form.as_table }}
    </table>
    <input class="submit" type="submit" value="modifica">
</form>

唯一的事情是,每次渲染form.html时,它都不会包含部分:

<script type="text/javascript" src="/the/script/that/should/handle/the/post.js">
</script>

我在这里做错了,显然是的,但我无法发现它。

欢迎任何反馈,谢谢!

2 个答案:

答案 0 :(得分:0)

如果您只是通过JavaScript直接转储HTML响应,那么这是正常的行为。您的浏览器(即所有这些)通过任意HTML字符串响应自动剥离由JS添加到页面的<script>标签作为安全预防措施。

答案 1 :(得分:0)

将相关的js / css脚本封装在表单中是一种很好的做法。 e.g。

class MyForm(forms.Form):
    field1 = ...
    field2 = ...
    class Media:
        js = ('script_that_handles_the_form.js',)

base.html中有一个像:

一样的块
{% block scripts %}
  <!--- some scripts that apply to all pages -->
{% endblock %}

然后在form.html

{% block scripts %}
  {{ block.super }}    # retain the standard scripts that apply everywhere
  {{ form.media }}     # add the form specific media/scripts
{% endblock %}

<form id="mod_form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
    <table class="form">
        {{ form.as_table }}
    </table>
    <input class="submit" type="submit" value="modifica">
</form>