需要提醒各位的是,上面的描述以及代码 只是验证自己 的想法, 不对正确性做校验,请各位看官小心
一.想法:假如已有一个页面,页面有一个表格,勾选表格中的记录,点击修改按钮,发起ajax get请求,通过django的views 返回form对象(后面证明无法返回一个form 对象,无奈只能返回一个 字符串)
1.在这个按钮增加了onclick="deleteSelect()" 触发deleteSelect()事件
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" onclick="deleteSelect()" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
2.deleteSelect() 方法,,其中获取name=choice,如果有被checked 的则会被加入到ids变量中,之后作为ajax的参数,接受接口的返回
(此处是允许被批量修改的,获取有一些问题,但是只要实现了我的想法,剩下的可以慢慢更改)
function deleteSelect() {
var chckBox = document.getElementsByName("choice");
var num = chckBox.length
var check_res;
var ids = "";
for (var index = 0; index < num; index++) {
if (chckBox[index].checked) {
ids += chckBox[index].value + ",";
}
}
if (ids != "") {
ids = ids.substring(0, ids.length - 1); //S 删除字符串最后一个字符的几种方法
ids = {
'ids': ids
}
$.ajax({
type: "get",
async:false,
url: "{% url 'product:edit_product' %}", //要自行删除的action
data: ids,
dataType: 'json',
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
$("#container").append(check_res);
$('#editMyModal').modal("show");
},
error: function (data) {
alert(data["form"]);
}
});
return check_res
} else {
alert("请选择要删除的记录");
}
}
4.最初的想法是返回一个bootstrap form 对象,(form = FormProduct(instance=product)),并在前端通过{bootstrap_form form })在前端显示,但是实验了很多方法无法 返回一个form对象,退而其次,返回一个字符串
return HttpResponse(json.dumps({
"form": str(form)
在ajax的接收:
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
$("#container").append(check_res);
$('#editMyModal').modal("show");
}
console.log(data["form"]); 打印的结果为
5.之后我们将这个字符串显示在 id=editMyModal 的modal中,
此时有2个方法:
① $("#container").append(check_res); 但是如果页面不刷新的话,则一直会在后面追加显示,所以此方法不适用
②.document.getElementById('container').innerHTML = check_res; ,此时发现一个致命的问题,就是无法加载样式,不管是在接口返回的时候就写好样式,还是接口返回之后在通过正则匹配的方式去追加样式,都太闹命伤财了
③.当然接口可以解析form 表单,返回json,然后通过js 获取该json,然后加载到html框架中(循环生成一些字符串样式(在里面放 value 属性),然后字符串通过 document.getElementById('container').innerHTML = check_res; )
④以上都是基于自己的一个思考过程,因为自己代码能力的限制,未能演示
下面的是参考别人较为成熟方案,帮助自己实现上述的想法;
以下是完整的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动化测试平台</title>
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/static/dist/css/AdminLTE.min.css">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="icon" type="image/png" href="/static/img/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!--产品列表-->
<div style="padding-top: 20px;padding-left: 200px ;padding-right: 200px">
<div class="col-sm-1">
<table>
<tr>
<td>
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" onclick="deleteSelect()" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
</td>
</tr>
</table>
</div>
<!-- /.box-header -->
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>产品名称</th>
<th>产品描述</th>
<th>产品负责人</th>
<th>状态</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><input id="radiobutton1" type="checkbox" value="{{ product.id }}" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue={{ product.id }} > {{ product.id }}</td>
<td style=' white-space: nowrap; text-overflow: ellipsis;overflow: hidden;' titlevalue={{ product.productname }}>{{ product.productname }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;" titlevalue={{ product.productdesc }}>{{ product.productdesc }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.producter }}>{{ product.producter }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.status }}> {{ product.status }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.create_time }}> {{ product.create_time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
编辑项目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="请输入id" >
</div>
<div class="form-group">
<label for="name">产品名称</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="请输入产品名称" required>
</div>
<div class="form-group">
<label for="desc">产品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="请输入产品描述" >
</div>
<div class="form-group">
<label for="user">产品负责人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="请输入产品负责人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 状态
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">关闭
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!--警告框-->
<div id="myAlert" style="display: none">
<strong>警告!</strong>编辑时只能勾选一条。
</div>
<div id="myAlert1" style="display: none">
<strong>警告!</strong>删除时一定要勾选一条。
</div>
<!-- DataTables -->
<script>
function deleteSelect() {
var chckBox = document.getElementsByName("choice");
var check_res;
var num = chckBox.length
var ids = "";
for (var index = 0; index < num; index++) {
if (chckBox[index].checked) {
ids += chckBox[index].value + ",";
}
}
if (ids != "") {
ids = ids.substring(0, ids.length - 1); //S 删除字符串最后一个字符的几种方法
ids = {
'ids': ids
}
$.ajax({
type: "get",
async:false,
url: "{% url 'product:edit_product' %}", //要自行删除的action
data: ids,
dataType: 'json',
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
document.getElementById('container').innerHTML = check_res;
$('#editMyModal').modal("show");
},
error: function (data) {
alert(data["form"]);
}
});
return check_res
} else {
alert("请选择要删除的记录");
}
}
//点击全选按钮勾选子节点操作
function demo(){
var allcheck=document.getElementById("allcheck");
var choice=document.getElementsByName("choice");
for(var i=0;i<choice.length;i++){
choice[i].checked=allcheck.checked;
}
}
//搜索或者搜索分页后去根据select返回的value去确定第几个option被选中
$(function(){
check();
});
//定义一个被选中的全局变量
var checkedenv_ids="{{ checkedenv_ids }}";
checkedenv_ids=checkedenv_ids.split(",");
// 根据返回值去勾选对应列
function check(){
//alert (checkedenv_ids);
//当前页的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert(env_id);
if (checkedenv_ids.includes(String(env_id))){
$(this).attr("checked", true);
}
}
});
//全选
setAll();
}
//根据当前页的勾选变化改变checkedenv_ids值
function change_checkedenv_ids(){
//当前页的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert($(this).attr("checked"));
//选中则判断数组是否存在,不存在则入栈
if ($(this).is(":checked")){
//alert(1);
//$(this).attr("checked", true);
if (!checkedenv_ids.includes(String(env_id))){
checkedenv_ids.push(String(env_id));
}
}
//未选中则判断数组是否存在,存在则出栈
else{
if (checkedenv_ids.includes(String(env_id))){
checkedenv_ids = $.grep(checkedenv_ids, function(value) {
return value != String(env_id);
});
}
}
}
});
//alert(checkedenv_ids);
}
function setAll(){
if(!$(".checknum").checked){
$("#allcheck").prop("checked",false); // 子复选框某个不选择,全选也被取消
}
var choicelength=$("input[type='checkbox'][class='checknum']").length;
var choiceselect=$("input[type='checkbox'][class='checknum']:checked").length;
if(choicelength==choiceselect){
$("#allcheck").prop("checked",true); // 子复选框全部部被选择,全选也被选择;1.对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法;2.对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
}
}
</script>
</body>
</html>
二.下面的则是借助别人的代码,供参考
先初始化
$(function(){
edit();
check();
});
edit 方法:其中需要关注的地方是 env[i]=env_value.attr('titlevalue'); 这个titlevalue是自定义属性,获取自定义属性的值,这个在后面会有说明;还有一个地方是$('#editMyModal').modal("show"); .modal 方法是Bootstrap 模态框(Modal)插件,可以打开id=editMyModal 的模态框,后面将贴出
function edit(){
$("#edit").click(function(){
$("#myAlert").css("display","none");
$("#myAlert1").css("display","none");
var count=0;
var env_value;
var env=new Array();
var elements=$(".ipt");
$("#table").find(":checkbox:checked.checknum").each(function(){
env_value=$(this).parent()
for (var i=0;i<elements.length;i++){
env_value=env_value.next()
//alert(email_value.text());
env[i]=env_value.attr('titlevalue');
}
//alert(env)
count++;
});
if (count==1)
{
//alert(env);
for (var i=0;i<env.length-1;i++){
$(elements[i]).val(env[i]);
}
if (env[env.length-1]=="True"){
$(elements[env.length-1]).prop('checked',true);
}
else{
$(elements[env.length-1]).removeAttr('checked');
}
$('#editMyModal').modal("show");
}
else{
$("#myAlert").css("display","inherit");
}
});}
此时查看id =editMyModal 的元素,其中aria-hidden="true" 默认隐藏,在edit 方法中$('#editMyModal').modal("show"); 弹出,其中在弹框中需要显示哪些值得,收class=ipt 的控制,因为在edit的方法中,会获取.ipt (var elements=$(".ipt");)
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
编辑项目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="请输入id" >
</div>
<div class="form-group">
<label for="name">产品名称</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="请输入产品名称" required>
</div>
<div class="form-group">
<label for="desc">产品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="请输入产品描述" >
</div>
<div class="form-group">
<label for="user">产品负责人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="请输入产品负责人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 状态
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">关闭
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
table 的代码如下:(在每一列都有titlevalue自定义属性,对应edit方法中的 env[i]=env_value.attr('titlevalue');)
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>产品名称</th>
<th>产品描述</th>
<th>产品负责人</th>
<th>状态</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue=1 > 1</td>
<td titlevalue=sdasdadasd>name</td>
<td titlevalue=desc>desc</td>
<td titlevalue=user>user</td>
<td titlevalue=True}> True</td>
<td titlevalue=今天> 今天</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="choice" class="checknum" ></td>
<td titlevalue="2" > 2</td>
<td titlevalue="name">name</td>
<td titlevalue="desc">desc</td>
<td titlevalue="user">user</td>
<td titlevalue="True"> True</td>
<td titlevalue="昨天"> 昨天</td>
</tr>
</tbody>
</table>
</div>
在此基础上,我们需要导入一些js和css 文件,即jquer.js ,bootstrap.js 和bootstrap.css(注意导入顺序)
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
其它代码将在完整代码中展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动化测试平台</title>
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!--产品列表-->
<div style="padding-top: 20px;padding-left: 200px ;padding-right: 200px">
<div class="col-sm-1">
<table>
<tr>
<td>
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
</td>
</tr>
</table>
</div>
<!-- /.box-header -->
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>产品名称</th>
<th>产品描述</th>
<th>产品负责人</th>
<th>状态</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue=1 > 1</td>
<td titlevalue=sdasdadasd>name</td>
<td titlevalue=desc>desc</td>
<td titlevalue=user>user</td>
<td titlevalue=True}> True</td>
<td titlevalue=今天> 今天</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="choice" class="checknum" ></td>
<td titlevalue="2" > 2</td>
<td titlevalue="name">name</td>
<td titlevalue="desc">desc</td>
<td titlevalue="user">user</td>
<td titlevalue="True"> True</td>
<td titlevalue="昨天"> 昨天</td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
编辑项目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="请输入id" >
</div>
<div class="form-group">
<label for="name">产品名称</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="请输入产品名称" required>
</div>
<div class="form-group">
<label for="desc">产品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="请输入产品描述" >
</div>
<div class="form-group">
<label for="user">产品负责人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="请输入产品负责人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 状态
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">关闭
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!--警告框-->
<div id="myAlert" style="display: none">
<strong>警告!</strong>编辑时只能勾选一条。
</div>
<div id="myAlert1" style="display: none">
<strong>警告!</strong>删除时一定要勾选一条。
</div>
<!-- DataTables -->
<script>
var check_res;
//点击全选按钮勾选子节点操作
function demo(){
var allcheck=document.getElementById("allcheck");
var choice=document.getElementsByName("choice");
for(var i=0;i<choice.length;i++){
choice[i].checked=allcheck.checked;
}
}
//搜索或者搜索分页后去根据select返回的value去确定第几个option被选中
$(function(){
edit();
check();
});
function edit(){
$("#edit").click(function(){
$("#myAlert").css("display","none");
$("#myAlert1").css("display","none");
var count=0;
var env_value;
var env=new Array();
var elements=$(".ipt");
$("#table").find(":checkbox:checked.checknum").each(function(){
env_value=$(this).parent()
for (var i=0;i<elements.length;i++){
env_value=env_value.next()
//alert(email_value.text());
env[i]=env_value.attr('titlevalue');
}
//alert(env)
count++;
});
if (count==1)
{
//alert(env);
for (var i=0;i<env.length-1;i++){
$(elements[i]).val(env[i]);
}
if (env[env.length-1]=="True"){
$(elements[env.length-1]).prop('checked',true);
}
else{
$(elements[env.length-1]).removeAttr('checked');
}
$('#editMyModal').modal("show");
}
else{
$("#myAlert").css("display","inherit");
}
});}
//定义一个被选中的全局变量
var checkedenv_ids="{{ checkedenv_ids }}";
checkedenv_ids=checkedenv_ids.split(",");
// 根据返回值去勾选对应列
function check(){
//alert (checkedenv_ids);
//当前页的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert(env_id);
if (checkedenv_ids.includes(String(env_id))){
$(this).attr("checked", true);
}
}
});
//全选
setAll();
}
//根据当前页的勾选变化改变checkedenv_ids值
function change_checkedenv_ids(){
//当前页的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert($(this).attr("checked"));
//选中则判断数组是否存在,不存在则入栈
if ($(this).is(":checked")){
//alert(1);
//$(this).attr("checked", true);
if (!checkedenv_ids.includes(String(env_id))){
checkedenv_ids.push(String(env_id));
}
}
//未选中则判断数组是否存在,存在则出栈
else{
if (checkedenv_ids.includes(String(env_id))){
checkedenv_ids = $.grep(checkedenv_ids, function(value) {
return value != String(env_id);
});
}
}
}
});
//alert(checkedenv_ids);
}
function setAll(){
if(!$(".checknum").checked){
$("#allcheck").prop("checked",false); // 子复选框某个不选择,全选也被取消
}
var choicelength=$("input[type='checkbox'][class='checknum']").length;
var choiceselect=$("input[type='checkbox'][class='checknum']:checked").length;
if(choicelength==choiceselect){
$("#allcheck").prop("checked",true); // 子复选框全部部被选择,全选也被选择;1.对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法;2.对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
}
}
</script>
</body>
</html>