首页 > 解决方案 > Python Flask - 避免在动态表返回渲染模板上发布

问题描述

我有这个 python 应用程序使用具有以下核心路由的烧瓶:

@app.route('/test_limit', defaults={'page':1})
@app.route('/test_limit/page/<int:page>')
def test_results_limit(page):
    perpage=10
    startat=page*perpage
    results = []
    cursor = db.cursor()
    cursor.execute('SELECT * from pi_fb_limit limit %s, %s;', (startat,perpage))
    table = list(cursor.fetchall())
    return render_template('results_limits.html', table=table)

@app.route('/infringement/FB/<int:id>')
def infringement(id):
    cursor = db.cursor()
    cursor.execute('UPDATE p_test_search SET infringement = ''TRUE'' WHERE ID = %s', (id))  
    db.commit()
    return render_template('results_limits.html')

在我的 HTML 文件“result_limits.html”中,我有这个 HTML 代码迭代 MySQL 结果:

 </table>
<tbody>
         {% for tab in table %}
            <tr class="zoomin">
               <th> {{tab[0]}} </th>
               <td> {{tab[9]}} </td>
               <td><button type="button" onclick="location.href='/infringement/FB/'+{{tab[0]}};return false;" class="btn btn-danger">Infringement</button></td>
            </tr>   
         {% endfor %}
        </tbody>
  </table>

一切正常,但我的问题是,当上面的按钮动态调用路由 @app.route('/infringement/FB/') 时,浏览器被重定向到 result_limits.html。相反,我想避免任何重定向并保持在同一页面上,每个行按钮正在创建帖子(以更新记录)。

有什么建议吗?谢谢 Regs SL

标签: pythonmysqlflask

解决方案


您需要使用 JavaScript 提交数据而无需重新加载页面。

就像是:

function submit_infringement(id) {
  this.removeAttribute('onclick');  // Prevent sumbitting twice.
  var x = new XMLHttpRequest();
  x.open('GET', '/infringement/FB/' + id, true);
  x.onload = function() {
    this.textContent = 'Infringement report sent!';
  }
  x.onerror = function(error) {
    (console.error || console.log)(error);
    this.textContent = 'An error occured. Try again.';
    this.onclick = function() { sumbit_infringemet(id); }
  }
  this.textContent = 'Sending infringement report...';
  x.send(null);
}
<td>
  <button type="button" onclick="sumbit_infringement({{tab[0]}});" class="btn btn-danger">
    Infringement
  </button>
</td>

推荐阅读