单击按钮即可从数据库中删除表行

Removing a table row from a db on a button click

本文关键字:删除 数据库 按钮 单击      更新时间:2023-09-26

我有一个表:

<table class="table" id="mytable">
  <tr>
    <td>Column 1</td>
    <td>Column 2</td>
    <td><button type="submit" class="btn removeButton">Remove</button></td>
  </tr>
</table>

在"removeButton"上单击我想删除给定的表行(它们将在之后动态创建)。我想用ajax发送来自这一行的数据,这样我也可以从数据库中删除它。我设法实现了从网站上删除行,但我在发送适当的请求和从请求中检索数据以将其从数据库中删除方面进展缓慢。

我的javascript代码:

$(document).ready(function() {
$('#mytable').on('click', '.removeButton', function(events){
    var data_array = $('td').map(function(){
        return $(this).serializeArray();
    });
    $(this).closest('tr').remove();
    $.ajax({
        type: "DELETE",
        data: data_array,
        success:function(result){
            window.location.href = $SCRIPT_ROOT + '/main';
        }
    });
  });
});

服务器端代码:

@app.route('/main', methods=['GET', 'POST', 'DELETE'])
def main():
  if request.method == 'POST':
    insert_in_db(request.form)
    return redirect(url_for('next_page'))
  elif request.method == 'DELETE':
    #Retrieve data from the request and remove it from the database
  return render_template('next_page.html')

如何在ajax请求中发送当前表行(单击按钮的旁边一行)的数据,之后如何在服务器端检索数据?我试着调用request.data,但只得到一个空字符串。我在DELETE请求中尝试了request.form,这给了我ImmutableMultiDict([])。有什么建议吗?我目前正在使用Flask作为web框架。谢谢

通过AJAX调用-发送行数据

$('#mytable').on('click', '.removeButton', function(events){
    var col1 = $(this).closest('tr').find('td').eq(0).html(); // or you could loop through the cells
    var col2 = $(this).closest('tr').find('td').eq(1).html();
    $(this).closest('tr').remove();
    $.ajax({
        type: "DELETE",
        data: {column1 : col1, column2 : col2}, // post values
        success:function(result){
            window.location.href = $SCRIPT_ROOT + '/main';
        }
    });
  });

这些应该在request.args 中可用