2012-05-07 36 views
0

我想從通過AJAX拉的「current.html」的JavaScript腳本塊沒有在Django模板渲染

處理表單視圖呈現「form.html」

「當前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> 

我在做什麼這裏錯了,顯然是的,但我無法發現它。

歡迎任何反饋,謝謝!

回答

0

如果您只是通過JavaScript直接轉儲HTML響應,那麼這是正常行爲。作爲安全防範措施,您的瀏覽器(即所有這些)會自動剝離由JS通過任意HTML字符串響應添加到頁面的<script>標籤。

+0

我想這是發生了什麼,因爲我的ajax成功函數加載在一個div結果(adiv.html(結果)); 有沒有解決這個問題的方法?我會嘗試什麼rantanplan建議,但我不擴展我的基地模板... – marlboro

+0

我想不出一種*易*的方式來解決它。你可以* JSON對錶單對象進行編碼,並在響應中包含JavaScript和URL,然後用JS手動創建表單和腳本標記。不過,我強烈建議只在你的主JS文件中包含表單JS,或者已經加載的任何頁面特定的JS。 –

+0

好吧,我意識到腳本沒有顯示在螢火蟲例如,但如果我讀源,腳本在那裏...但是我注意到,如果我分配給腳本字符集屬性爲utf-8,一切似乎好的..在IE7以及:) – marlboro

0

在您的表單中封裝相關的js/css腳本是一種很好的做法。 例如

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>