基于Layui的页面传参及获取参数

预计实现效果

通过点击编辑按钮,能够把该行数据显示在表格中

  • table.html页面所属表格截取一行:

  • edit.html页面:

实现代码

  • table.html关键代码,传递参数
// 监听更新(编辑)操作
table.on('tool(currentTableFilter)', function (obj) {
      var st_id = obj.data.id;
      var st_username = obj.data.username;
      var st_grade = obj.data.grade;
      var st_department = obj.data.department;
      var st_dorm = obj.data.dorm;
      var st_sex = obj.data.sex;
      var st_phone = obj.data.phone;
      var st_email = obj.data.email;
      if (obj.event === 'edit') { 
            var index = layer.open({
                  title: '编辑用户',
                  type: 2,
                  shade: 0.2,
                  maxmin: true,
                  shadeClose: true,
                  area: ['55%', '90%'],
                  content: '../table/edit/edit.html?st_id='+st_id+'&st_username='+escape(st_username)+'&st_grade='+st_grade+'&st_phone='+st_phone+
                  '&st_department='+escape(st_department)+'&st_dorm='+escape(st_dorm)+'&st_sex='+escape(st_sex)+'&st_email='+st_email,
            });
      }
}
  • edit.html关键代码(js):接收参数并放进输入框
function getQueryString(name) { 
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); 
    var r = window.location.search.substr(1).match(reg); 
    if (r != null) { 
        return unescape(r[2]); 
    } 
    return null; 
}

//接收table.html的编辑按钮传递的参数
var phone = getQueryString("st_phone");
var id = getQueryString("st_id");
var username = unescape(getQueryString("st_username"));
var dorm = unescape(getQueryString("st_dorm"));
var grade = getQueryString("st_grade");
var email = getQueryString("st_email");
var department = unescape(getQueryString("st_department"));

//将参数赋值给input输入框
document.getElementsByName("phone")[0].value = phone;
document.getElementsByName("id")[0].value = id;
document.getElementsByName("username")[0].value = username;
document.getElementsByName("dorm")[0].value = dorm;
document.getElementsByName("email")[0].value = email;
document.getElementsByName("department")[0].value = department;
document.getElementsByName("grade")[0].value = grade;

问题

  • 遇到问题①:传参中文乱码
    解决方法:在table.html使用escape包裹传入参数,在edit.html用unescape获取传进的参数,列子见上方username、dorm、department参数

  • 遇到问题②:弹出的页面性别一栏固定选中了“男”
    解决方法,因php需要用到name传参,增加了一个id来区分男女选项,根据传入的性别修改checked状态,实现选中对应选项。

<input type="radio" name="sex" value="男" title="男" id="male" checked="">
<input type="radio" name="sex" value="女" title="女" id="female" checked="">
var sex = unescape(getQueryString("st_sex"));
//使弹窗打开可根据传入性别选中对应选项
if(sex=='男'){
    document.getElementById("male").checked=true;
    document.getElementById("female").checked=false;
}else{
    document.getElementById("male").checked=false;
    document.getElementById("female").checked=true;
}
posted @ 2020-07-04 22:08  crush-w  阅读(24714)  评论(0编辑  收藏  举报