2018-10-24:Ajax完成预约效果
2018-10-25 本文已影响0人
神坛下的我
ajax完成预约效果
- 保证浏览器访问action能够得到json数据集合(检查浏览器输出)。
- 先做好静态的表格带基本的样式,通过ajax方法,将回调函数返回的预约信息,循环变成td,组装到table中,不需要了静态的tr和td,由于涉及日期处理,需要解决如何获取当前日期,如何获取当前日期所在的周次,如何获得当前日期本周一的日期,通过将日期编号等关键信息生成到td的属性中,以便匹配(检查ajax回调函数返回的内容能否正确生成表头信息包括日期和星期几)。
- 通过本周周一和周五的循环内部和返回的数据集遍历双重循环,找到日期和半天匹配的信息,通过判断生成不同的td样式,显示不同的界面效果(检查本周数据是否正确生成)。
- 将生成部分需要封装的方法提取出来,将原来的代码完整剪切 用function封装,将代码中变量不是自己声明的就需要传参,在原位置调用方法传参(检查封装后已完成功能是否受影响 如本周th,td和下一周th,td逐步封装)。
- 追加切换按钮,一定要在ajax回调函数中调用方法追加。(因为ajax 有可能先执行但是后执行完,可能造成需要的数据集还没有从服务器取回来),再追加封装的click方法(检查按钮能不能点,点了能不能切换本周和下一周)。
- 通过点击时间和本td属性中保存的日期和上下午,和数据集合比对找到需要的其他数据,添加的公共的div用于显示(公共div需要定位和父元素偏移,检查先不隐藏公共的div,调整完毕才隐藏)。
实体类:Appointment.java
package entity;
public class Appointment {
private String apno;// 编号由日期-上午 例如 2018-10-24-1 表示2018-10-24上午
private String apname;//预约姓名
private String apsex;//预约性别
private String apphone;//预约电话
private String apdesc;//预约描述
public Appointment() {
super();
}
public Appointment(String apno, String apname, String apsex, String apphone, String apdesc) {
super();
this.apno = apno;
this.apname = apname;
this.apsex = apsex;
this.apphone = apphone;
this.apdesc = apdesc;
}
public String getApno() {
return apno;
}
public void setApno(String apno) {
this.apno = apno;
}
public String getApname() {
return apname;
}
public void setApname(String apname) {
this.apname = apname;
}
public String getApsex() {
return apsex;
}
public void setApsex(String apsex) {
this.apsex = apsex;
}
public String getApphone() {
return apphone;
}
public void setApphone(String apphone) {
this.apphone = apphone;
}
public String getApdesc() {
return apdesc;
}
public void setApdesc(String apdesc) {
this.apdesc = apdesc;
}
}
Action类:AppointmentAction.java
package action;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServlet;
import org.apache.struts2.ServletActionContext;
import entity.Appointment;
import net.sf.json.JSONArray;
import utils.MyDateFormat;
public class AppointmentAction extends HttpServlet{
private static final long serialVersionUID = 1L;
private List<Appointment> appointments;
private String currentDate;//获取当前要查看的是第几个星期
private int currentWeek;//当前在本年周次
public String getCurrentDate() {
return currentDate;
}
public void setCurrentDate(String currentDate) {
this.currentDate = currentDate;
this.currentWeek = MyDateFormat.getWeekOfYear(currentDate);
}
/**
* @see HttpServlet#HttpServlet()
*/
public AppointmentAction() {
super();
appointments = new ArrayList<Appointment>();
Appointment appointment1 = new Appointment("2018-10-10-1", "张阿姨", "女", "111", "成都,60岁");
Appointment appointment2 = new Appointment("2018-10-24-2", "陈阿姨", "女", "151", "合肥,50岁");
Appointment appointment3 = new Appointment("2018-10-25-1", "何叔叔", "男", "111", "成都,57岁");
Appointment appointment4 = new Appointment("2018-10-26-1", "李叔叔", "男", "121", "南京,63岁");
Appointment appointment5 = new Appointment("2018-10-31-1", "庄阿姨", "女", "168", "自贡,65岁");
Appointment appointment6 = new Appointment("2018-10-29-2", "张阿姨", "女", "133", "镇江,66岁");
appointments.add(appointment1);
appointments.add(appointment2);
appointments.add(appointment3);
appointments.add(appointment4);
appointments.add(appointment5);
appointments.add(appointment6);
}
/**
* @see 获得本周和下一周的 预约
*/
public String getCurrentAndNextWeekAppointment() throws Exception {
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getRequest().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().setContentType("text/html; charset=utf-8");
PrintWriter out = ServletActionContext.getResponse().getWriter();
//需要将全部的预约中 是本周和下一周的 保留为新的集合
List<Appointment> realAppointments = new ArrayList<Appointment>();
//循环每一个预约,和当前标准时间对应的周次 一致 或者为下一周的才保留
for(Appointment appointment:appointments){
String appointmentDate = appointment.getApno().substring(0, appointment.getApno().length()-2);
int appointmentWeek = MyDateFormat.getWeekOfYear(appointmentDate);
if(appointmentWeek == currentWeek || appointmentWeek == currentWeek + 1){
//System.out.println(appointmentDate);
realAppointments.add(appointment);
}
}
JSONArray jsondetails = JSONArray.fromObject(realAppointments);
out.print(jsondetails.toString());
return null;
}
public String addAppointment() throws Exception {
return null;
}
public String updateAppointment() throws Exception {
return null;
}
}
工具类:MyDateFormat.java
package utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MyDateFormat {
//传入日期,获取日期所在的星期 是全年的第多少个星期
public static int getWeekOfYear(String date) {
//格式化日期类
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date resultDate = null;
try {
//格式化日期
resultDate = format.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//时间类 传入
Calendar calendar = Calendar.getInstance();
//设置一周的开始为周一
calendar.setFirstDayOfWeek(Calendar.MONDAY);
//传入需要 比对的日期
calendar.setTime(resultDate);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
//System.out.println(weekOfYear);
return weekOfYear;
}
public static void main(String[] args) {
MyDateFormat.getWeekOfYear("2018-10-24");
}
}
struts.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="struts2" extends="struts-default" namespace="/">
<action name="appointmentAction_*" class="action.AppointmentAction" method="{1}">
<allowed-methods>addAppointment,updateAppointment,getCurrentAndNextWeekAppointment</allowed-methods>
</action>
</package>
</struts>
预约.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
</style>
<style type="text/css">
.content{margin-left:auto;margin-right:auto;width: 1000px;}
.appointment{margin-left:auto;margin-right:auto;width: 800px;border:solid 1px;}
.appointment tr > td{width:140px;border:solid 1px;text-align: center;height:28px;}
.appointment tr > td:nth-child(1){width:100px;}
.stateTd > span{display:inline-block; width:36px;height:20px;margin-top:4px;}
.stateTd1 > span{background-image: url('image/car.png');background-position: 0px -340px;}
.stateTd2 > span{background-image: url('image/car.png');background-position: -60px -340px;}
.apppointTab{position: relative;}
.detailinfo{display: none;position: absolute;}
.detailinfo > ul{margin:0;padding:0;}
.detailinfo > ul > li{list-style-type: none;font-family: "微软雅黑";font-size: 12px;}
.detailinfo > ul > li:nth-child(even){background-color: #fde4eb;}
.detailinfo > ul > li:nth-child(odd){background-color: #e3fbe3;}
.content > div > input{margin-left:780px;margin-top:10px;}
.currentWeek{display: none;}
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/dateformat.js"></script>
<script type="text/javascript" src="js/initAppointment.js">
</script>
<script type="text/javascript">
$(function(){
//alert('1254');
})
</script>
</head>
<body>
<div class="content">
<div class="apppointTab">
<table class="appointment">
</table>
<div class="detailinfo"></div>
</div>
<div>
</div>
</div>
</body>
</html>
dateformat.js:
//获取当前时间,格式YYYY-MM-DD
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate;
}
//获取是当前星期的 日期,dayno 本周的第几天
function getCurrentWeekDay(dayno){
var dd = new Date();
var week = dd.getDay(); //获取时间的星期数
//alert(week);
var minus = week ? week - 1 : 6;
//alert(minus);
dd.setDate(dd.getDate() - minus + dayno); //获取minus天前的日期
var y = dd.getFullYear();
var m = dd.getMonth() + 1; //获取月份
var d = dd.getDate();
return y + "-" + m + "-" + d;
}
function getDayofWeek(day){
var weekday=new Array(7);
weekday[0]="星期一";
weekday[1]="星期二";
weekday[2]="星期三";
weekday[3]="星期四";
weekday[4]="星期五";
weekday[5]="星期六";
weekday[6]="星期日";
var dd = new Date(day);
var week = dd.getDay();
var dayofweek = week ? week - 1 : 6;
return weekday[dayofweek];
}
initAppointment.js
$(function(){
//alert(getCurrentWeekDay(5));
$.ajax({
url:'appointmentAction_getCurrentAndNextWeekAppointment.action',
type:'post',
data:{'currentDate':getNowFormatDate()},
dataType:'json',
success:function(appointments){
//alert(appointments);
//$details = $(details);//js对象转换为jquery对象
//appendDiv();//该方法的调用方在success才能保证ajax取到值之后,才循环
initTh(1);
initTd(appointments,1,1);
initTd(appointments,2,1);
//初始化按钮
var btnstr = '<input type="button" value="本周" class="changeWeekBtn currentWeek"/>'
+'<input type="button" value="下一周" class="changeWeekBtn nextWeek"/>'
$('.content >div:eq(1)').append(btnstr);
btnbindClick(appointments);//追加绑定按钮事件
}
});
function initTh(currentOrNext){
var trOfth = '<tr><th>时间段</th>';
var day;
for(var i=0;i<5;i++){
if(currentOrNext==1){
day = getCurrentWeekDay(i);
}else{
day = getCurrentWeekDay(i+7);
}
trOfth += '<th>'+day+'<br/>('+getDayofWeek(day)+')</th>';
}
trOfth += '</tr>';
$('.appointment').append(trOfth);
}
function initTd(appointments,halfday,currentOrNext){
var trRow;
if(halfday == 1){
trRow = "<tr><td>上午</td>";
}else{
trRow = "<tr><td>上午</td>";
}
var findflag;
for(var i=0;i<5;i++){
findflag = false;//标志本次循环是否找到有相对应的半天预约信息
if(currentOrNext==1){
day = getCurrentWeekDay(i);
}else{
day = getCurrentWeekDay(i+7);
}
//在外部循环出的日期 和,数据库返回的预约日期 进行匹配(上午)
$(appointments).each(function(j,appointment){
var appointmentDate = appointment.apno;
if(appointmentDate.substr(0,10)==day
&&appointmentDate.substr(11,1)==halfday){
trRow += '<td class="stateTd stateTd2" alt="'+day+'" alt1="'+halfday+'"><span></span></td>';
findflag = true;
//break;
}
});
if(findflag == false){
trRow += '<td class="stateTd stateTd1"><span></span></td>';
}
}
trRow += "</tr>";
$('.appointment').append(trRow);
tdbindHover(appointments);//给新生成的td绑定 鼠标移入移出事件
}
//按钮绑定,一定在ajax回调中使用,才能保证有数据
function btnbindClick(appointments){
$('.changeWeekBtn').click(function(){
if($(this).val()=='下一周'){
$('.currentWeek').css("display",'block');
$('.nextWeek').css("display",'none');
//因为已经将初始化th 和上午td 下午td 分别封装到了方法,通过最后一个参数区别本周和下一周
$('.appointment').html('');
initTh(2);
initTd(appointments,1,2);
initTd(appointments,2,2);
}else{
$('.currentWeek').css("display",'none');
$('.nextWeek').css("display",'block');
$('.appointment').html('');
initTh(1);
initTd(appointments,1,1);
initTd(appointments,2,1);
}
});
}
//td鼠标移入移出事件
function tdbindHover(appointments){
$('.stateTd2').hover(function(e){
var currentApno= $(this).attr('alt')+'-'+$(this).attr('alt1');
//遍历数据集合找到 当前半天对应的数据
var currentAppointment;
$(appointments).each(function(i,appointment){
if(appointment.apno ==currentApno){
currentAppointment = appointment;
}
});
var tdulStr = '<ul>';
tdulStr += '<li><span>姓名:</span>'+currentAppointment.apname+'<span></span>';
tdulStr += '<li><span>性别:</span>'+currentAppointment.apsex+'<span></span>';
tdulStr += '<li><span>电话:</span>'+currentAppointment.apphone+'<span></span>';
tdulStr += '<li><span>描述:</span>'+currentAppointment.apdesc+'<span></span>';
tdulStr += '</ul>';
//将内容添加给公共的div显示
$('.detailinfo').html(tdulStr);
var clientX = e.clientX;
var clientY = e.clientY;
var parentLeftPx = $('.apppointTab').css('marginLeft');
var parentTopPx = $('.apppointTab').css('marginTop');
//alert(schoolbgleftPx.length);
var parentLeft = parentLeftPx.substr(0,parentLeftPx.length-2);
var parentTop = parentTopPx.substr(0,parentTopPx.length-2);;
$('.detailinfo').css('left',clientX-parentLeft).css('top',clientY-parentTop).css('display','block');
},function(){
$('.detailinfo').html('');
$('.detailinfo').css('display','none');
});
}
});