实战Flask+BootstrapTable后端传javascript脚本给前端实现多行编辑(ajax方式)

相信看到此文的朋友们一定会感到庆幸,总之我是用了两天死磕,才得到如下结果,且行且珍惜,祝好各位!

话不多说,有图有源码

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, '&quot;');
}
//行编辑数据更新到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)
#=============================================================

就这些了,如果你有更好的方法,望不吝赐教!

相关推荐
崔庆才丨静觅1 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60612 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了2 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅2 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅3 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅3 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax