【问题标题】:flask forms and javascript烧瓶形式和 javascript
【发布时间】:2012-07-19 14:59:27
【问题描述】:

你好,我有下面的 html 代码

<form>
<input type="text" id="filepathz" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>

javascript 代码

  window.onload = init;

  function init() {
          var button = document.getElementById("spotButton");
          button.onclick = handleButtonClick;
  }       

  function handleButtonClick(e) {
          var filepathz = document.getElementById("filepathz");

         var path = filepathz.value;

         if (path == "") {
                 alert("give a filepath");
         }else{
                 var url = "http://localhost:5000/tx/checkme/filepathz=" + path;
                 window.open (url,'_self',false);
         }       
 } 

还有烧瓶上的python代码

def index():
        """Load start page where you select your project folder
        or load history projects from local db"""
        from txclib import get_version
        txc_version = get_version()
        prj = project.Project(path_to_tx)

        # Let's create a resource list from our config file
        res_list = []
        prev_proj = ''
        for idx, res in enumerate(prj.get_resource_list()):
                hostname = prj.get_resource_host(res)
        username, password = prj.getset_host_credentials(hostname)
        return render_template('init.html', txc_version=txc_version, username=username)

    @app.route('/tx/checkme/<filepathz>')
    def checkme(filepathz):
            filepathz = request.args.get('filepathz')
            return render_template('init.html', txc_version=filepathz)

我做错了什么,无法从表单(filepathz)中获取数据

【问题讨论】:

  • 您能否验证您的事件是否触发? (带有console.log)?并且那个 filepathz 变量在 onclick 事件中不是未定义的?
  • 不,它工作正常 javascript 部分。它还会打开新链接localhost:5000/tx/checkme/filepathz="USERS INPUT",但不会将其传递给 python!

标签: javascript python html get flask


【解决方案1】:

您没有正确传递变量。传递变量有两种方式:

1) 通过 get 方法传递:

http://localhost:5000/tx/checkme/?filepathz=" + path; (Note the '?')

目前您正在尝试从 request.args 获取变量,但没有在请求中传递它,这就是为什么您没有得到。

2) 从带有flask的url结构的url中获取:

在 JS 中执行此操作:http://localhost:5000/tx/checkme/" + path

在你看来:

@app.route('/tx/checkme/<filepathz>')
def checkme(filepathz):
      return render_template('init.html', txc_version=filepathz) # You can use this variable directly since you got it as a function arguement.

【讨论】:

  • 如果你通过 GET 传递它,你的视图装饰器应该是:@app.route('/tx/checkme/'),因为请求变量不是 url 结构的一部分。跨度>
猜你喜欢
  • 2017-09-03
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多