【问题标题】:Python Flask - avoid posting on dynamic table return to render template [duplicate]Python Flask - 避免发布动态表返回渲染模板[重复]
【发布时间】:2018-11-04 00:55:33
【问题描述】:

我有这个 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。 相反,我想避免任何重定向并保持在同一页面上,每个行按钮正在创建帖子(以更新记录)。

有什么建议吗? 谢谢 注册 SL

【问题讨论】:

    标签: python mysql flask


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 1970-01-01
      • 2023-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多