Python Flask - 避免在动态表上发布返回渲染模板

时间:2018-05-24 17:52:52

标签: python mysql flask

我有这个python app使用具有这个核心路径的烧瓶:

@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

1 个答案:

答案 0 :(得分:1)

您需要使用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>
相关问题