bootStrap基础 前后台数据交互方法



//处理火狐与谷歌不兼容此事件的触发方式
$("body").keydown(function(e) {????????
	e = e ? e : window.event;
	var keyCode = e.which ? e.which : e.keyCode;
	//回车键的键值为13	
	if(keyCode == 13){
	document.getElementById("login").click();
	}
});

//登录
function login() {	
	if($("#username").val() == null || $("#username").val() == ""){
		alert("账号为空");
		return;
	}
	if($("#password").val() == null || $("#password").val() == ""){
		alert("密码为空");
		return;
	} 
	$.ajax({
		type: "POST",
		url: "${admin_path}/login",
		data: {username:$("#username").val(), password:$("#password").val()},
		dataType: "json",					
		success: function(r) {
			if(r.retCode == 200) {
				parent.location.href = '${admin_path}/index';
			} else {
				parent.layer.alert(r.message,{icon:2})
			}
		},
	});				
}

//select下拉框显示信息
$.ajax({
    type: "post",
    url: prefix + "/businessSupplier/list",
    dataType: "json",
    success: function(data) {
        if(data.retCode == 200) {
            var temp = data.data.code;
            for(var i = 0; i < temp.length; i++) {
                if (supplierCode2 == temp[i].supplier_code) {
                    $("#supplierCode").append(""); //此处向select中循环绑定数据
                } else {
                    $("#supplierCode").append(""); //此处向select中循环绑定数据
                }
            }
        } else {
            alert(data.message);
        }
    },
    error: function() {
        alert("error");
    }
});

//select二级联动
$.ajax({
	type: "post",
	url: adminPath + "/company/getUserCompanyInfo",
	data: {
		userId: userId
	},
	dataType: "json",
	success: function(data) {
		if(data.retCode == 200) {
			var strdata = JSON.stringify(data);
			$("#userId").val(userId);
			$("#companyName").val(data.data.code.company_name);
			$("#mobilePhone").val(data.data.code.mobile_phone);
			$("#email").val(data.data.code.email);
			$("#employeesTotalNum").val(data.data.code.employees_total_num);
			var temp = data.data.parent;//显示行业类型
			for(var i = 0; i < temp.length; i++) {				
				if(temp[i].enterprise_type_code == data.data.enterprise[0].parent_code) {
					$("#parentTypeCode").append("");
				} else {
					$("#parentTypeCode").append("");
				}
			}
			var temp2 = data.data.enterprise;
			for(var j = 0; j < temp2.length; j++) {
				if(temp2[j].id == data.data.code.enterprise_type_id) {
					$("#enterpriseTypeCode").append("");
				} else {
					$("#enterpriseTypeCode").append("");
				}
			}
		} else {
			alert(data.message);
		}
	},
	error: function() {
		alert("error");
	}

});

$('#parentTypeCode').on('change', function(e, params) {	
	$.ajax({ //select二级联动
		type: "POST",
		url: adminPath + "/baseEnterpriseType/listBaseEnterpriseType",
		dataType: 'json',
		data: {
			parentTypeCode: $("#parentTypeCode").val(),
			enterpriseTypeCode: $("#enterpriseTypeCode").val()
		},		
		success: function(data) {
			var arr = Object.keys(data.data.code);
			if(state==arr){
				//$("#parentTypeCode").html("");
				var code = data.data.code[arr];
				for(var i = 0; i < code.length; i++) {
					$("#parentTypeCode").append(""); //此处向select中循环绑定数据
				}
			}
			
			var state = $('#parentTypeCode').val();
			var arr2 = Object.keys(data.data.code);
			for(var i = 0; i < arr2.length; i++) {
				if(state == arr2[i]) {					
					$("#enterpriseTypeCode").html("");
					var codes = data.data.code[arr2[i]];
					for(var j = 0; j < codes.length; j++) {
						$("#enterpriseTypeCode").append("");
					}
				}
			}
		}
	});
});

//ajax赋值 编辑信息
$.ajax({
    type: "post",
    url: prefix + "/businessMaterial/info",
    data: {id:id},
    dataType: "json",
    success: function(data){
        if (data.retCode == 200) {
            var strdata = JSON.stringify(data);
            $("#materialCode").val(data.data.code.material_code);
            $("#materialModel").val(data.data.code.material_model);          
        } else {
            alert(data.message);
        }
    },
});

//ajax提交
function save() {
    if($("#signupForm").valid()){
        $.ajax({
            cache : true,
            type : "POST",
            url : prefix + "/orderPurchaseRecordDetail/save" ,
            data : $('#signupForm').serialize(),
            success : function(data) {
                if (data.retCode == 200) {
                    parent.layer.msg("操作成功",{icon:1});
                    parent.reLoad();
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                } else {
                    parent.layer.alert(data.message,{icon:2});
                }
            }
        });
    }
}


$.ajax({
	type: "post",
	url: prefix + "",
	data: {deviceCode2: deviceCode},
	dataType: "json",
	success: function(data) {	
		if(data.retCode == 200) {			
			var list = data.data.code
				if(list.length > 0) {
					$.each(list, function(i, v) {
						$("#id").val(v.id);
						$("#deviceName").val(v.device_name);						
					})
				}					
		} else {
			alert(data.message);
		}
	},
	error: function() {
		alert("error");
	}
});

// 页面跳转弹框
function dan(id, supplier_code) {
    layerMax=layer.open({
        type: 2,
        title: '增加订单',
        maxmin: true,
        shadeClose: false,
        area: ['800px', $(window).height()*0.7+'px'],
        content: prefix + '/orderPurchaseRecordDetail/toSave?id='+id + "&supplierCode2=" + supplier_code,
    });
    layer.full(layerMax);
}

//表格显示bootstrap
function load2() {
	$('#exampleTable2')
		.bootstrapTable({
			method: 'get',
			url: prefix + "/device/userList?deviceCode=" + deviceCode,
			iconSize: 'outline',
			toolbar: '#exampleToolbar',
			striped: true,
			dataType: "json",
			pagination: true,
			singleSelect: false,
			pageSize: 10,
			pageNumber: 1,
			showColumns: false,
			sidePagination: "client",
			queryParams: function(params) {
				return {
					userId: userId,
					userName:$("#userName").val(),
				};
			},
			responseHandler(data) {
				var expiredArr = data.data.expired
				var notExpiredArr = data.data.notExpired
				var masterArr = data.data.master
				var allArr = []
				if(masterArr.length > 0) {
					$.each(masterArr, function(i, v) {
						v.isExpired = ''
						allArr.push(v)
					})
				}
				if(notExpiredArr.length > 0) {
					$.each(notExpiredArr, function(i, v) {
						v.isExpired = 'notExpired'
						allArr.push(v)
					})
				}
				if(expiredArr.length > 0) {
					$.each(expiredArr, function(i, v) {
						v.isExpired = 'expired'
						allArr.push(v)
					})
				}
				return allArr
			},
			columns: [{
					checkbox: true
				},
				{
					field: 'id',
					title: 'ID'
				},
				{
					field: 'user_id',
					title: '用户id'
				},
				{
					field: 'user_name',
					title: '姓名'
				},
				{
					field: 'status',
					title: '状态',
					formatter: function(value, row, index) {
						//console.log(row.isExpired)
						/*var expiredArr = row.data.expiredArr
						var notExpiredArr = row.data.notExpiredArr*/
						//console.log(row.status)
						if(row.status == undefined) {
							if(row.isExpired == 'notExpired') {
								return "已生效";
							} else if(row.isExpired == 'expired') {
								return "已失效";
							}
						} else {
							if(row.status == "1") {
								return "已生效";
							}
							if(row.status == "0") {
								return "已失效";
							}
						}
					}
				},
				{
					filed: 'time',
					title: '时效',
					formatter: function(value, row, index) {
						var string_time = ''
						if(row.user_type == "管理员") {
							string_time = '无限制'
							var weekDay = ''
						} else if(row.user_type == "1"){
							string_time = '无限制'
							var weekDay = ''
						}else if(row.user_type == "2") {
							var tv = "每周";
							var date = [
								"日",
								"一",
								"二",
								"三",
								"四",
								"五",
								"六"
							];
							for(var i = 0; i < row.week.length; i++) {
								if(Number(row.week.substring(i, i + 1)) == 1) {
									if(i == row.week.length - 1) {
										tv = tv + date[i];
									} else {
										tv = tv + date[i] + "、";
									}
								}
							}
							var str = row.begin_time.substring(row.begin_time.length - 8);
							var str2 = row.end_time.substring(row.end_time.length - 8);
							string_time = tv + str + '--' + str2
							console.log(row.begin_time + '-' + row.end_time)
						} else if(row.user_type == "3") {
							string_time = row.begin_time + '-' + row.end_time
						}
						return string_time
					}
				},
				{
					field: 'user_type',
					title: '身份',
					formatter: function(value, row, index) {
						if(row.user_type =="管理员") {
							return "无限制";
						}
						if(row.user_type == "1") {
							return "无限制";
						}
						if(row.user_type == "2") {
							return "经常用户";
						}
						if(row.user_type == "3") {
							return "临时用户";
						}
					}
				},
				{
					title: '操作',
					field: 'button',
					align: 'center',
					formatter: function(value, row, index) {
						if(row.user_type == "管理员") {
						// 	var d = ' ';
						// return d;
						}else{
							var a = ' ';
						var d = ' ';
						return /*a +*/ d;
						}												
					}
				}
			]
		});
}

		
//搜索 function reLoad2() { $('#exampleTable2').bootstrapTable('refresh'); } //删除表格 function remove(id) { layer.confirm('确定要删除选中的记录?', { btn: ['确定', '取消'] }, function() { layer.load(2, { shade: [0.2,'#999999'] }); $.ajax({ url: prefix + "/businessMaterial/remove", type: "post", data: { 'id': id }, success: function(r) { if(r.retCode == 200) { layer.msg("删除成功",{icon:1}); layer.closeAll('loading'); reLoad(); } else { layer.msg(r.message,{icon:2}); layer.closeAll('loading'); } } }); }) } //通过 function edit(status,company_code) { layer.confirm('确定要通过申请吗?', { btn: ['确定', '取消'] }, function() { layer.load(2, { shade: [0.2,'#999999'] }); $.ajax({ url: prefix+ "/user/auditCompany", type: "get", data: { 'companyCode': company_code, 'status': 1, }, success: function(r) { if(r.retCode == 200) { layer.msg("成功",{icon:1}); layer.closeAll('loading'); reLoad2(); } else { layer.msg(r.message,{icon:2}); layer.closeAll('loading'); } } }); }) } //接收ID格式转换 function GetRequest() { var url = location.search; var theRequest = new Object(); if(url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]); //unescape } } return theRequest; } var Request = new Object(); Request = GetRequest(); var userId = Request['userId']; var deviceCode = Request['deviceCode']; $("#userId").text(userId); //多选删除 function batchRemove() { var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行,当没有选择的记录时,返回一个空数组 if(rows.length == 0) { layer.msg("请选择要删除的数据"); return; } layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", { btn: ['确定', '取消'] }, function() { var ids = new Array(); $.each(rows, function(i, row) { ids[i] = row['roleId']; }); console.log(ids); $.ajax({ type: 'POST', data: { "ids": ids }, url: prefix + '/batchRemove', success: function(r) { if(r.code == 0) { layer.msg("删除成功",{icon:1}); reLoad(); } else { layer.msg(r.msg,{icon:2}); } } }); }, function() {}); } //jstree function getTreeData(){ $.ajax({ type: "GET", dataType: "json", contentType: "application/x-json", url: prefix + '/department/list?userId=' + userId, success: function(tree) { loadTree(tree); } }); } function loadTree(tree) { console.log(JSON.stringify(tree.data.code)) $('#jstree').jstree({ 'core': { 'data': tree.data.code, }, "plugins": ["search"] }); $('#jstree').jstree().open_all(); } $('#jstree').on('changed.jstree',function(e,data){//获取jstree点击的值 var departmentId = data.instance.get_node(data.selected[0]).id; $("#departmentId").val(data.instance.get_node(data.selected[0]).id); var deptName = data.instance.get_node(data.selected[0]).text; $("#deptName").val(data.instance.get_node(data.selected[0]).text); }); //js校验 $(document).ready(function(){ $.validator.setDefaults({ submitHandler: function(form) { form.submit(); } }); //手机号码验证身份证正则合并:(^\d{15}$)|(^\d{17}([0-9]|X)$) jQuery.validator.addMethod("isPhone",function(value,element){ var length = value.length; var phone=/^1[3|4|5|7|8][0-9]\d{8}$/; return this.optional(element)||(length == 11 && phone.test(value)); },"请填写正确的11位手机号"); //电话号码验证 jQuery.validator.addMethod("isTel",function(value,element){ var tel = /^(0\d{2,3}-)?\d{7,8}$/g;//区号3,4位,号码7,8位 return this.optional(element) || (tel.test(value)); },"请填写正确的座机号码"); //姓名校验 jQuery.validator.addMethod("isName",function(value,element){ var name=/^[\u4e00-\u9fa5]{2,6}$/; return this.optional(element) || (name.test(value)); },"姓名只能用汉字,长度2-4位"); //校验用户名 jQuery.validator.addMethod("isUserName",function(value,element){ var userName=/^[a-zA-Z0-9]{2,13}$/; return this.optional(element) || (userName).test(value); },'请输入数字或者字母,不包含特殊字符'); //校验身份证 jQuery.validator.addMethod("isIdentity",function(value,element){ var id= /^(\d{15}$|^\d{18}$|^\d{17}(\d|X))$/; return this.optional(element) || (id.test(value)); },"请输入正确的15或18位身份证号,末尾为大写X"); //校验出生日期 jQuery.validator.addMethod("isBirth",function(value,element){ var birth = /^(19|20)\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$/; return this.optional(element) || (birth).test(value); },"出生日期格式示例2000-01-01"); //校验新旧密码是否相同 jQuery.validator.addMethod("isdiff",function(){ var p1=$("#oldPassword").val(); var p2=$("#pwdNew").val(); if(p1==p2){ return false; }else{ return true; } }); //校验新密码和确认密码是否相同 jQuery.validator.addMethod("issame",function(){ var p3=$("#password").val(); var p4=$("#pwdNew").val(); if(p3==p4){ return true; }else{ return false; } }); //校验基础信息表单 $("#basicInfoForm").validate({ errorElement:'span', errorClass:'help-block error-mes', rules:{ userName:{ required:true, isUserName:true }, sex:"required", birth:"required", mobilePhone:{ required:true, isPhone:true }, email:{ required:true, email:true } }, messages:{ userName:{ required:"请输入账号", isUserName:"请输入数字或者字母" }, sex:{ required:"请输入性别" }, birth:{ required:"请输入出生年月" }, mobilePhone:{ required:"请输入手机号", isPhone:"请填写正确的11位手机号" }, email:{ required:"请输入邮箱", email:"请填写正确的邮箱格式" } }, errorPlacement:function(error,element){ element.next().remove(); element.closest('.gg-formGroup').append(error); }, highlight:function(element){ $(element).closest('.gg-formGroup').addClass('has-error has-feedback'); }, success:function(label){ var el = label.closest('.gg-formGroup').find("input"); el.next().remove(); label.closest('.gg-formGroup').removeClass('has-error').addClass("has-feedback has-success"); label.remove(); }, submitHandler:function(form){ alert("保存成功!"); } }); //校验修改密码表单 $("#modifyPwd").validate({ onfocusout: function(element) { $(element).valid()}, debug:false, //表示校验通过后是否直接提交表单 onkeyup:false, //表示按键松开时候监听验证 rules:{ oldPassword:{ required:true, minlength:9 }, pwdNew:{ required:true, minlength:9, isdiff:true, //issame:true, }, password:{ required:true, minlength:9, issame:true, } }, messages:{ oldPassword : { required:'必填', minlength:$.validator.format('密码长度要大于9') }, pwdNew:{ required:'必填', minlength:$.validator.format('密码长度要大于9'), isdiff:'原密码与新密码不能重复', }, password:{ required:'必填', minlength:$.validator.format('密码长度要大于9'), issame:'新密码要与确认新密码一致', } }, errorElement:"mes", errorClass:"gg-star", errorPlacement: function(error, element) { element.closest('.gg-formGroup').append(error); } }); }); //转换日期格式(时间戳转换为datetime格式) function changeDateFormat(date) { var strDate = new Date(date).toJSON(); return new Date(+new Date(strDate) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') } formatter: function (value) { return changeDateFormat(value) } $("#quoteTime").val(changeDateFormat(data.data.code.quote_time).substring(0,10));编辑框日期格式截取年月日 //时间控件 class="laydate-icon form-control layer-date" laydate({ elem: '#endTime', format: 'YYYY-MM-DD', istoday: true, start: laydate.now(0, "YYYY/MM/DD"), istime: true, choose: function(date) { console.log(date) $('#exportEndTime').val($('#endTime').val()); } }); //获取短信内容 radio取值赋值 $.ajax({ type:"post", url:prefix+"/message/info", data:{id:id}, datatype:"json", success :function (data) { if(data.retCode==200){ $("#aspName").val(data.data.code.asp_name); $("#priority").val(data.data.code.priority); $("#switchingPeak").val(data.data.code.switching_peak); $("#limitPerMinute").val(data.data.code.limit_per_minute); $("#limitPerHour").val(data.data.code.limit_per_hour); $("#limitPerDay").val(data.data.code.limit_per_day); $("#price").val(data.data.code.price); if (parseInt(data.data.code.enable) == 1) { //radio取值赋值 $('input:radio:first').attr('checked', 'true'); } else { $("input:radio[value='0']").attr('checked', 'true'); } $("#remark").val(data.data.code.remark); } } }); //multiselect多选框赋值 //导入bootstrap_multiselect 全选303 $.ajax({ type : "POST", url :prefix + "/businessEnterpriseRole/findOrganizationModule", dataType : "json", success : function(data) { var temp = data.data.info; for (var i = 0; i < temp.length; i++) { $("#roleSet").append(""); } $("#roleSet").multiselect("destroy").multiselect({ // 自定义参数,按自己需求定义 nonSelectedText : '--请选择--', maxHeight : 350, includeSelectAllOption : true, numberDisplayed : 5 }); } }); Echarts动态加载图表数据 function load(){ // 基于准备好的dom,初始化echarts图表 var main = echarts.init(document.getElementById('userCharts')); var beginTime = document.getElementById('beginTime').value; var endTime = document.getElementById('endTime').value; $.ajax({ url : prefix + "/data/newUserAndCompany", type: "post", data: {"beginTime": beginTime,"endTime": endTime}, dataType: "json", success:function (data) { var timeList = data.data.timeList; var newUserList = data.data.newUserList; var newCompanyList = data.data.newCompanyList; console.log(timeList); main.setOption({ title : { text: '' }, tooltip : { trigger: 'axis' }, legend: { data:['新增用户','新增企业'] }, grid:{ x:30, x2:40, y2:24 }, calculable : true, xAxis : [ { type : 'category', data : timeList } ], yAxis : [ { type : 'value' } ], series : [ { name:'新增用户', type:'bar', data:newUserList }, { name:'新增企业', type:'bar', data:newCompanyList } ] }) } }) } /*$('.summernote').summernote({ callbacks: { // onImageUpload callback onImageUpload: function(files) { // upload image to server and create imgNode... var data = new FormData(); data.append("file", files[0]); $.ajax({ data : data, type : "POST", url:prefix+"/owsArticle/imageUpload", //图片上传出来的url,返回的是图片上传后的路径,http格式 cache : false, contentType : false, processData : false, dataType : "json", success: function(data) {//data是返回的hash,key之类的值,key是定义的文件名 console.log(data.data); $('.summernote').summernote('insertImage', data.data[0],'img'); }, error:function(){ alert("上传失败"); } }); } } });*/ // 公用属性 var adminPath = $("#adminPath").val(); var prefix = adminPath; var id = $("#id").val(); $.ajax({ type: "post", url: prefix + "/project/getProjectUpdateDetail", data: {id:id}, dataType: "json", success: function(data){ if (data.code == 200) { $("#name").val(data.data.project.name); $("#estimate").val(data.data.project.estimate); $("#desc").val(data.data.project.desc); // 项目附件列表 var projectAttachList = data.data.projectAttachList; // 项目成员列表 var projectTeamList = data.data.projectTeamList; // 成员列表 var userList = data.data.userList; // 项目需求列表 var projectRequirementList = data.data.projectRequirementList; // 项目信息 var project = data.data.project; // 需求列表 var requirementList = data.data.requirementList; // 显示成员列表 for (var i = 0; i < userList.length; i++) { $("#team").append(""); } // 勾选成员 for (var i = 0; i < userList.length; i++) { $("#team option").each(function () { var val = $(this).val(); for (var j = 0; j < projectTeamList.length; j++) { if (val == projectTeamList[j].id) { $(this).attr("selected", "selected"); } } $("#team").multiselect("destroy").multiselect({ // 成员多选 nonSelectedText : '--请选择--', maxHeight : 350, numberDisplayed : 5 }); }) } // 显示需求列表 for (var i = 0; i < requirementList.length; i++) { $("#requirementIds").append(""); } // 勾选需求 for (var i = 0; i < requirementList.length; i++) { $("#requirementIds option").each(function () { var val = $(this).val(); for (var j = 0; j < projectRequirementList.length; j++) { if (val == projectRequirementList[j].requirementId) { $(this).attr("selected", "selected"); } } $("#requirementIds").multiselect("destroy").multiselect({ // 需求多选 nonSelectedText : '--请选择--', maxHeight : 350, numberDisplayed : 5 }); }) } // 负责人 for(var i = 0; i < userList.length; i++) { if (project.projectLeaderId == userList[i].id) { $("#projectLeaderId").append(""); } else { $("#projectLeaderId").append(""); } } // 附件列表 for(var i = 0; i < projectAttachList.length; i++) { $.each(projectAttachList, function(i, v) { $("#fileId").val(v.id); $("#delAttachs").val(v.attachName); }) } } else { alert(data.message); } }, }); //下载文件 function download(){ var form=$("
");//定义一个form表单 form.attr("method","get"); form.attr("action","/project/download");//请求url var input1=$(""); input1.attr("type","hidden"); input1.attr("name","id");//设置属性的名字 input1.attr("value",$("#fileId").val());//设置属性的值 $("body").append(form);//将表单放置在web中 form.append(input1); form.submit();//表单提交 } //上传文件及其他字段 function update() { var formData = new FormData(); var id = $.trim($("#id").val()); var name = $.trim($("#name").val()); var requirementIds = $.trim($('#requirementIds').val()); var projectLeaderId = $.trim($('#projectLeaderId').val()); var estimate = $.trim($('#estimate').val()); var desc = $.trim($('#desc').val()); var files = $("#files")[0].files[0]; var team = $.trim($('#team').val()); var delAttachs = $.trim($('#delAttachs').val()); formData.append('id', id); formData.append('requirementIds', requirementIds); formData.append('name', name); formData.append('projectLeaderId', projectLeaderId); formData.append("estimate",estimate); formData.append("desc",desc); formData.append("files",files); formData.append("team",team); formData.append("delAttachs",delAttachs); if($("#signupForm").valid()){ $.ajax({ type : "POST", url : prefix + "/project/changeProject", data : formData, cache : false, processData : false, contentType : false, success : function(data) { if (data.code == 200) { parent.layer.msg("操作成功",{icon:1}); parent.reLoad(); var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); } else { parent.layer.alert(data.message,{icon:2}); } } }); } }

 

你可能感兴趣的:(JS,bootStrap,js,layui,前后台数据交互)