在javascript中,会经常用到回调的方式,比如,当某一请求执行完成后,要完成某一指定的动作,但是程序无法知道请求什么时候完成,这时我们便可以使用回调来实现,像ajax就用到了回调的概念。下面,笔者列举自己在项目中用到的两个实例。
首先,来看看js代码:
function postRequest(object, callback) {
//请求之前,显示遮罩层,以及loading图标
window.top.$('#maskCell').show();
window.top.$('#loadImg').show();
$.post(object.url, object.param, function(data){
//请求成功之后,隐藏遮罩层以及loading图标
window.top.$('#maskCell').hide();
window.top.$('#loadImg').hide();
callback(data);
});
}
再来看看调用的js代码:
$(function(){
//Get data by user id
var id = $('#detailUserId').val();
// $.getJSON('sys/user/getEntity.do', {'id': id}, function(data) {
// console.log(data);
//
// //加载数据到表单
// $('#singleUserDlogForm').form('load',data);
// });
postRequest({
url:'sys/user/getEntity.do',
param: {'id':id}
}, function(data) {
console.log(data);
//加载数据到表单
$('#singleUserDlogForm').form('load',data);
});
});
这里,每当请求完成后去掉遮罩层,并通过回调完成特定的任务。
首先,来看看页面:
这里,点击开始导入,导入成功后便要重新加载datagrid。
注意,此导入窗口在父窗口中,datagrid数据表格在iframe中,所以笔者这里会将回调函数名从iframe窗口传到导入窗口。
下面来看看userlist.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Cache-Control" CONTENT="no-cache">
<title>User List</title>
<link rel="stylesheet" type="text/css" href="resources/jquery-easyui-1.4.2/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="resources/jquery-easyui-1.4.2/themes/icon.css">
<link rel="stylesheet" type="text/css" href="resources/logicCSS/user/listUser.css">
</head>
<body>
<h2>User List</h2>
<div>
<form id="queryForm">
ID:<input type="text" name="id"/> 姓名:<input type="text" name="userName"/> <a href="javascript:void(0);" id="search">搜索</a>
</form>
</div>
<a type="import" id="import" class="easyui-menubutton" callback="myCallback">导入</a>
<!-- 导出 -->
<a type="export" id="export" class="easyui-menubutton">导出</a>
<!-- 表格 -->
<div data-options="region:'center'" class="tab">
<table id="userListTab"></table>
</div>
<script type="text/javascript" src="resources/jquery-easyui-1.4.2/jquery-1.8.0.js"></script>
<script type="text/javascript" src="resources/jquery-easyui-1.4.2/jquery.easyui.min.js"></script>
<script type="text/javascript" src="resources/logicJS/common/common.js"></script>
<script type="text/javascript"> var basePath = '<%=basePath %>'; console.log('currentMenu:', window.top.currentMenu); console.log('basePath:', basePath); </script>
<script type="text/javascript" src="resources/logicJS/user/listUser.js"></script>
</body>
</html>
然后,再来看看其对应的listUser.js:
$(function() {
console.log('windows是否一致', window === window.top);
//初始化导出按钮
initMyExportMenu();
//添加搜索按钮点击事件
$('#search').click(function() {
search();
});
//添加导入点击事件
$('#import').click(function() {
console.log('弹出导入对话框。。');
//获取回调函数名
var callbackName = $(this).attr('callback');
//用户详情对话框
var importWindow = window.top.$('#importWin');
if(importWindow.length <= 0) {
importWindow = window.top.$("<div id='importWin'/>").appendTo(window.top.document.body);
}
importWindow.window({
title:'导入',
closed: false,
closable: true,
draggable: true,
resizable: true,
width: 400,
height: 300,
modal: true,
href: 'sys/redirect/redirectHomePage.do?path=import&callback=' + callbackName,
onClose: function() {
importWindow.window("destroy");
}
});
});
//加载userlist到datagrid中去,使用datagrid默认分页机制
$("#userListTab").datagrid({
fit:true,
fitColumns:true,
collapsible:false,
nowrap: true,
autoRowHeight: true,
striped: true,
url: 'sys/user/getPageModel.do',
idField : 'id',
remoteSort: true,
loadMsg: 'Please wait...',
checkOnSelect:false,
singleSelect: false,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[[
{field:'id',title:'用户id',sortable:true},
{field:'userName',title:'用户姓名',sortable:true},
{field:'age',title:'用户年龄',sortable:true},
{field:'opt',title:'操作', align:'center', formatter:function(value,rec, index) {
return '<a id="detail" href="javascript:void(0);" onclick="detail(' + rec.id +')">查看</a> <a id="edit" href="javascript:void(0);" onclick="edit(' + rec.id + ')">编辑</a> <a id="delete" href="javascript:void(0);" onclick="deleteUser(' + rec.id + ')">删除</a>';
}}
]],
//工具栏:添加、批量删除
toolbar: [{
id: 'btnAdd',
text: 'Add',
iconCls:'icon-add',
handler:function() {
edit();
}
}, '-', {
id:'btnDelete',
text: 'Delete',
iconCls:'icon-cut',
handler: function() {
var rows = $("#userListTab").datagrid('getChecked');
var array = [];
$.each(rows, function(index, row){
array.push(row.id);
});
deleteUser(array);
}
}],
pagination:true,
pageSize: 5,
pageList: [3,4,5],
onLoadSuccess:function(data){
console.log(data);
}
});
//分页
var p = $('#userListTab').datagrid('getPager');
$(p).pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
onBeforeRefresh:function(){}
//onSelectPage: function(pageNumber, pageSize) {} --此事件添加,就会导致当页码或页大小变化时,不向后台发送请求
});
});
//查看详情
function detail(id) {
//用户详情对话框
var addWindow = window.top.$('#detailWin');
if(addWindow.length <= 0) {
addWindow = window.top.$("<div id='detailWin'/>").appendTo(window.top.document.body);
}
addWindow.window({
title:'用户详情',
closed: false,
closable: true,
draggable: true,
resizable: true,
width: 900,
height: 600,
modal: true,
href: 'sys/redirect/redirectHomePage.do?path=user_detail&id=' + id,
onClose: function() {
addWindow.window("destroy");
}
});
}
//添加和编辑,共用
function edit(id) {
//编辑用户对话框
var addWindow = window.top.$('#saveOrEditUserWin');
if(addWindow.length <= 0) {
addWindow = window.top.$("<div id='saveOrEditUserWin'/>").appendTo(window.top.document.body);
}
addWindow.window({
title:'添加和编辑用户',
closed: false,
closable: true,
draggable: true,
resizable: true,
width: 900,
height: 600,
modal: true,
href: 'sys/redirect/redirectHomePage.do?path=user_save&id=' + id,
onClose: function() {
addWindow.window("destroy");
}
});
}
//删除
function deleteUser(ids) {
var array = [];
//判断是单个删除,还是多个删除
if(typeof(ids) === 'number') {
array.push(ids);
} else {
array = ids;
}
//删除确认
window.top.$.messager.confirm('警告', '你确定要删除吗?', function(result){
if(result) {
// $.post(baseURL + '/user/deleteEntity.do', {ids: array}, function(data){
// window.top.$.messager.alert('提示', '删除成功!!');
//
// //Reload data
// $("#userListTab").datagrid('reload');
// });
postRequest({
url: 'sys/user/deleteEntity.do',
param: {ids: array}
}, function(data) {
window.top.$.messager.alert('提示', '删除成功!!');
//Reload data
$("#userListTab").datagrid('reload');
});
}
});
}
//搜索
function search() {
var params = [];
//自动序列化表单元素为JSON对象
var fields =$('#queryForm').serializeArray();
console.log(fields);
$.each(fields, function(i, field){
if(field.name === 'id' && $.trim(field.value) === '') {
field.value = 0;
}
params[field.name] = field.value;
});
console.log('params', params['userName']);
//重新加载数据
$('#userListTab').datagrid('load',params);
}
/** * 初始化导出按钮 */
function initMyExportMenu(){
var exportsubmenu = '<div id="exportMenu_sub">'+
'<div id="export_crrent"><span class="exportcurrent"></span>导出当前页</div>'+
'<h1 class="excel-line"></h1>'+
'<div id="export_all"><span class="exportall"></span>导出全部</div>'+
'</div>';
$("body").append(exportsubmenu);
var exports = $("a[type='export']");
$.each(exports,function(data){
var exportMenu = $(this).menubutton({
menu: "#exportMenu_sub",
iconCls:"icon-export"
});
$(exportMenu.menubutton('options').menu).menu({
onHide:function(){
},
onClick: function (item) {
if(item.id=="export_crrent"){
console.log('导出当前页');
var options = $('#userListTab').datagrid('getPager').data("pagination").options;
var curr = options.pageNumber;
console.log('当前页:', curr);
var pageSize = options.pageSize;
console.log('页大小', pageSize);
//通过隐藏域传参数
// $("#queryForm").form('submit',{
// url : 'tm/illegalBusinessWebsiteDetail/exportillegalBusiness.do',
// onSubmit : function() {
// return $(this).form('validate');
// },
// success : function(data) {
// }
// });
}
if(item.id=="export_all"){
console.log('导出全部');
// $("#queryForm").form('submit',{
// url : 'tm/illegalBusinessWebsiteDetail/exportillegalBusiness.do',
// onSubmit : function() {
// return $(this).form('validate');
// },
// success : function(data) {
// }
// });
}
}
});
});
}
/** * 回调函数 * @returns */
function myCallback(name) {
console.log('回调函数执行。。' + name);
//重新加载datagrid
$("#userListTab").datagrid('reload');
}
最后,再来看导入窗口页面import.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String callback = request.getParameter("callback"); System.out.println("回调函数为:" + callback); %>
<script type="text/javascript"> var callback = '<%=callback%>'; console.log('callback:', callback); </script>
<div style="width:100%;height:100%;position:relative;">
<button id="startImport" style="position:relative;top:224px;left:50px;height:20px;">开始导入</button>
</div>
<script type="text/javascript" src="resources/logicJS/common/common.js"></script>
<script type="text/javascript" src="resources/logicJS/common/import.js"></script>
其对应的js,import.js:
$(function() {
console.log('windows是否一致', window === window.top);
$('#startImport').click(function() {
console.log('开始导入');
var iframe = $('#mainPanel > iframe' ,window.top.document)[0];
var currentChildWindow = iframe.contentWindow || iframe.window;
console.log('callback', callback);
currentChildWindow[callback]('qiyongkang');
});
});
最后,点击‘开始导入’按钮后,控制台的输入如下图:
说明,回调成功啦!
今天,就讲到这儿啦,有些没讲清楚或是有问题的地方,欢迎大家指出,谢谢!