如何在表单提交前更改表单操作

2024-09-29 21:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个连接到python后端的html表单。表单包含一个文件上载字段

如果提交时文件字段为空,我希望表单操作更改为“http://localhost:5000/nofile

如果文件字段包含提交时的值,我希望表单操作更改为“http://localhost:5000/containsfile

以下是我尝试过的:

 <script>
   function formFunc(){
     if (document.getElementById("file").files.length == 0)
        document.getElementById("mainform").action = "http://localhost:5000/nofiles";
      } else {
        document.getElementById("mainform").action = "http://localhost:5000/containsfiles"
      }
</script>

  <form onclick="formFunc()" name="mainform" method="POST" action=""
     enctype = "multipart/form-data">
     <input type = "file" id="file" name = "file" />
     <input type = "submit"/>
  </form>

我也尝试过在我的表单中使用onsubmit()和onclick()函数,但都不起作用


Tags: 文件nameformlocalhosthttp表单inputscript
1条回答
网友
1楼 · 发布于 2024-09-29 21:50:01

你犯了一些基本的错误:

  • 你忘了函数中的一些{}
  • 你没有id="mainform"

工作代码

from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return '''<script>
function formFunc(){
  if (document.getElementById("file").files.length == 0) {
    document.getElementById("mainform").action = "http://localhost:5000/nofiles";
  } else {
    document.getElementById("mainform").action = "http://localhost:5000/containsfiles";
  }
}
</script>

<form onclick="formFunc()" id="mainform" method="POST" action="" enctype="multipart/form-data">
   <input type="file" id="file" name="file" />
   <input type="submit" />
</form>'''

app.run()

相关问题 更多 >

    热门问题