相信看到此文的朋友们一定会感到庆幸,总之我是用了两天死磕,才得到如下结果,且行且珍惜,祝好各位!
话不多说,有图有源码
1.看图
2.前端实现页面
<!DOCTYPE html>
{% from "common/_macro.html" import static %}
<html>
<meta charset="utf-8">
<head>
<!-- 引入bootstrap样式 -->
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" />
<!-- 引入bootstrap-table样式 -->
<link rel="stylesheet" href="/static/bootstrap-table-develop/bootstrap-table.min.css" />
<!-- layer -->
<link rel="stylesheet" href="/static/layer/2.4/skin/layer.css" />
<!-- jquery -->
<script type="text/javascript" src="/static/js/jquery-2.2.0.min.js" ></script>
<!-- bootstrap -->
<script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js" ></script>
<!-- bootstrap-table -->
<script type="text/javascript" src="/static/bootstrap-table-develop/bootstrap-table.min.js" ></script>
<!-- 引入中文语言包 -->
<script type="text/javascript" src="/static/bootstrap-table-develop/locale/bootstrap-table-zh-CN.min.js" ></script>
<!-- layer -->
<script type="text/javascript" src="/static/layer/2.4/layer.js" ></script>
</head>
<body class="gray-bg">
<h1 align="center">Bootstrap-Table 多行编辑保存</h1>
<div class="wrapper wrapper-content ">
<div class="col-sm-12">
<div class="ibox">
<div class="ibox-body">
<table id="exampleTable"></table>
<button type="button" id="butSave" class="btn btn-primary col-sm-1 col-sm-offset-5" onclick="save()">保存</button>
</div>
</div>
</div>
</div>
<div ></div>
</body>
</html>
<script>
var prefix = "/hellotableeditrowssave";
var $table = $('#exampleTable');
$(function() {
var loadData = [];
var tableColumns = [];
initTable();
ajaxTable('/hellotableeditrowssave/ajaxlist');
function initTable() {
$table.bootstrapTable({
toolbar: '#toolbar',
clickEdit: true,
showToggle: true,
pagination: true, //显示分页条
showColumns: true,
showPaginationSwitch: true, //显示切换分页按钮
showRefresh: true, //显示刷新按钮
//clickToSelect: true, //点击row选中radio或CheckBox
columns: tableColumns
});
}
function ajaxTable(url){
//debugger;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(rs){
console.log(rs)
loadData = rs.data.rows;
tableColumns = eval(rs.data.columns);//JSON.parse(rs.data.columns);//'('++')'
$table.bootstrapTable('refreshOptions',
{
columns: tableColumns,
data: loadData,
});
//-----隐藏id列
//$table.bootstrapTable('hideColumn','id');
},
error: function(rs){
console.log(rs)
}
});
}
});
//对象转json字符串
function objTostr(obj){
if( typeof(obj)!=='object' ){return obj;}
var temp=Object.assign({},obj);
return JSON.stringify( temp).replace(/"/g, '"');
}
//行编辑数据更新到table中
function editRow(index,field,value,row){
alert("修改了id="+row.id+" 字段名: ["+field+"] 的内容:['"+value+"']");
var rows = {
index : index, //更新列所在行的索引
field : field, //要更新列的field
value : value //要更新列的数据
};//更新表格数据
$("#exampleTable").bootstrapTable("updateCell",rows);
}
function save(){
var rows = $table.bootstrapTable('getSelections');
if (rows.length == 0) {
alert("请选择要保存的记录!");
return;
} else {
var params = JSON.stringify(rows);
$.ajax({
url : '/hellotableeditrowssave/update',
type : 'POST',
data : params,
contentType:'application/json;charset=utf-8',
dataType:'JSON',
cache : false,
success : function(data) {
layer.msg(data.data.msg);
}
});
}
}
</script>
3.后端内容
#=============================================================
#---------------------阿桂天山 Ewangda--------------------------
"""
Bootstrap-table 动态多行编辑保存
"""
@app.route('/hellotableeditrowssave', methods=['GET','POST'])
def hellotableeditrowssave():
return render_template('/hello_tableeditrowssave.html')
@app.route('/hellotableeditrowssave/ajaxlist', methods=['GET','POST'])
def hellotableeditrowssave_ajaxlist():
columns = """[{'checkbox': true}, {'field': 'id','title': 'Item ID'}, {'field': 'name1','title': 'Item Name'}, {'field': 'price','title': 'Item Price'},
{'field': 'goods','title': '商品', 'formatter': function(value, row, index, field) { if (row['goods'] == "" || row['goods'] == null){
value = "";} else { value = row['goods']; } var abc = "hahaha"; return '<input class="form-control" value="'+value+'" name="goods" type="text" onblur="editRow(\\''+index+'\\',\\'goods\\',this.value,'+objTostr(row)+');">';}}]"""
datas = [{ "id": 11, "name1": "gtj", "price": "¥11", "goods": "玩具小车" },
{ "id": 22, "name1": "Ewangda", "price": "¥22", "goods": "遥控赛车" },
{ "id": 31, "name1": "小柘服务", "price": "¥32", "goods": "翻斗车" }]
data = {
'columns' : columns,
'rows' : datas
}
totalNum = 3
return restful.success(data=data) #{'total': totalNum, 'data':datas}) #
@app.route('/hellotableeditrowssave/update', methods=['GET','POST'])
def hellotableeditrowssave_update():
result = request.get_json()
num = len(result)
ids =[]
for row in result:
print(row['id'],row['goods'])
ids.append(row['id'])
# print(result)
data ={
'msg': "成功修改{0}条记录:ids={1}".format(num,ids)
}
return restful.success(data=data)
#=============================================================
就这些了,如果你有更好的方法,望不吝赐教!