使用javascript在django表单中设置操作

时间:2017-04-23 21:13:45

标签: javascript jquery html django post

django 1.10中,我需要将参数从一个html模板传递回view.py,最后再渲染相同的视图。

问题在于在html中设置action以使用javascript。

这是我的html模板:

<form method='POST' action='/res/{{link}}/{{page_id}}/{{email}}/'> 
      <input type="hidden" name="email" value="{{email}}">
      <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}>
</form> 
{{page_id}}中的{p> action随着用户与网页的交互而变化(使用下拉选择器)。以下javascript可以捕获这个:

<script>
function post_redirect_link() {
    var page_id = document.getElementById("sel1").options.selectedIndex;
    return '/res/{{link}}/'+page_id+'/{{email}}/'  
}
</script>

我尝试将action动态设置为:

<form method='POST' action='post_redirect_link()'> 
      <input type="hidden" name="email" value="{{email}}">
      <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}>
</form> 

但相反,我得到了/res/correct_link/post_redirect_link()/correct_email类型的重定向,其中&#34; post_redirect_link()&#34;被视为字符串而不是js方法返回的值。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

尝试执行以下操作。

<form action="#" method='POST'>
  <script>
     function changeAction() {
         var page_id = document.getElementById("sel1").options.selectedIndex;
         var url = '/res/{{link}}/'+page_id+'/{{email}}/';
         document.forms[0].action = url;
     }
  </script>
  <input type="hidden" name="email" value="{{email}}">
  <input type="image" type='submit' onmouseover="changeAction()" src={% static "assets/images/twitter_icon.png" %}>

</form>