【问题标题】:Using Flask url_for in button onclick location.href redirect leads to `Method Not Allowed`在按钮 onclick location.href 中使用 Flask url_for 重定向导致“方法不允许”
【发布时间】:2017-03-18 05:56:30
【问题描述】:

我正在对一些基本形式进行线框设计,但遇到了意想不到的405 Method Not Allowed 拦截器。

基本上我在 jinja 模板中有一些 html,看起来像......

<!--Select File Y-->
<tr>
    <td>File Y</td>
    <td>{{form.pathY }}</td>
    <td><input type=file name=browse ></td>
    <td><button onclick="window.location.href='{{ url_for( 'dataTablePage' , table='Y' ) }}';">Display Table Y</button></td>
</tr>
<tr>
    <td/>
    <td/>
    <td/>
    <td><a href="{{ url_for( 'dataTablePage' , table='Merged' ) }}">View Merged Data</a></td>
</tr>

在 DOM 中,这或多或少地呈现了我对 location.href = '/DataTable/Y/' 的期望

但是,当我单击按钮时,我会在 405 Method Not Allowed 页面中结束。

另一方面,当我使用 url_for 从锚点重定向时,重定向按预期工作。在按钮的 onclick 重定向中使用 url_for 有什么用?

不确定是否重要,但这是我要连接的路线...

@app.route('/DataTable/<table>/')
def dataTablePage(table) :
    """
    Takes the user to the Table View corresponding to the given table parameter
    """
    table == "X" :
        dfTable = DataFrame( data = {"X1":[1,2,3] , "X2":[2,3,4]} ) 
    elif table == "Y" :
        dfTable = DataFrame( data = {"Y1":[1,2,3,4,5] , "Y2":[2,3,4,5,6]} ) 
    elif table == "Merged" :
        dfTable = DataFrame( data = {"M1":[1,2] , "M2":[2,3]} ) 
    else :
        redirect( url_for('error') )

    return render_template( 'dataTable.html' , filePath="x.csv" , headers=dfTable.columns.values.tolist() , table=dfTable.iterrows() )

【问题讨论】:

    标签: flask jinja2


    【解决方案1】:

    这实际上是您的 HTML 的问题,default "type" of button is:

    缺失值默认为提交按钮状态。

    而且由于您没有指定按钮的类型,它只是尝试提交表单,这会导致 405 问题。

    将您的按钮类型更改为"button",它应该可以按预期工作:

    <button type="button" onclick="window.location.href='{{ url_for( 'dataTablePage' , table='Y' ) }}';">Display Table Y</button>
    

    【讨论】:

    • 实心,甚至没有意识到按钮有types 看起来default 类型是submit,现在这很有意义发生了什么。
    猜你喜欢
    • 2014-11-04
    • 2020-07-21
    • 2022-12-11
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多