ajax完成預(yù)約效果
- 保證瀏覽器訪問action能夠得到j(luò)son數(shù)據(jù)集合(檢查瀏覽器輸出)。
- 先做好靜態(tài)的表格帶基本的樣式惠爽,通過ajax方法丧诺,將回調(diào)函數(shù)返回的預(yù)約信息,循環(huán)變成td髓帽,組裝到table中菠赚,不需要了靜態(tài)的tr和td,由于涉及日期處理郑藏,需要解決如何獲取當(dāng)前日期衡查,如何獲取當(dāng)前日期所在的周次,如何獲得當(dāng)前日期本周一的日期必盖,通過將日期編號(hào)等關(guān)鍵信息生成到td的屬性中拌牲,以便匹配(檢查ajax回調(diào)函數(shù)返回的內(nèi)容能否正確生成表頭信息包括日期和星期幾)。
- 通過本周周一和周五的循環(huán)內(nèi)部和返回的數(shù)據(jù)集遍歷雙重循環(huán)歌粥,找到日期和半天匹配的信息塌忽,通過判斷生成不同的td樣式,顯示不同的界面效果(檢查本周數(shù)據(jù)是否正確生成)失驶。
- 將生成部分需要封裝的方法提取出來砚婆,將原來的代碼完整剪切 用function封裝,將代碼中變量不是自己聲明的就需要傳參突勇,在原位置調(diào)用方法傳參(檢查封裝后已完成功能是否受影響 如本周th装盯,td和下一周th,td逐步封裝)甲馋。
- 追加切換按鈕埂奈,一定要在ajax回調(diào)函數(shù)中調(diào)用方法追加。(因?yàn)閍jax 有可能先執(zhí)行但是后執(zhí)行完定躏,可能造成需要的數(shù)據(jù)集還沒有從服務(wù)器取回來)账磺,再追加封裝的click方法(檢查按鈕能不能點(diǎn)芹敌,點(diǎn)了能不能切換本周和下一周)。
- 通過點(diǎn)擊時(shí)間和本td屬性中保存的日期和上下午垮抗,和數(shù)據(jù)集合比對(duì)找到需要的其他數(shù)據(jù)氏捞,添加的公共的div用于顯示(公共div需要定位和父元素偏移,檢查先不隱藏公共的div冒版,調(diào)整完畢才隱藏)液茎。
實(shí)體類:Appointment.java
package entity;
public class Appointment {
private String apno;// 編號(hào)由日期-上午 例如 2018-10-24-1 表示2018-10-24上午
private String apname;//預(yù)約姓名
private String apsex;//預(yù)約性別
private String apphone;//預(yù)約電話
private String apdesc;//預(yù)約描述
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;//獲取當(dāng)前要查看的是第幾個(gè)星期
private int currentWeek;//當(dāng)前在本年周次
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", "鎮(zhèn)江栋烤,66歲");
appointments.add(appointment1);
appointments.add(appointment2);
appointments.add(appointment3);
appointments.add(appointment4);
appointments.add(appointment5);
appointments.add(appointment6);
}
/**
* @see 獲得本周和下一周的 預(yù)約
*/
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();
//需要將全部的預(yù)約中 是本周和下一周的 保留為新的集合
List<Appointment> realAppointments = new ArrayList<Appointment>();
//循環(huán)每一個(gè)預(yù)約,和當(dāng)前標(biāo)準(zhǔn)時(shí)間對(duì)應(yīng)的周次 一致 或者為下一周的才保留
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 {
//傳入日期挺狰,獲取日期所在的星期 是全年的第多少個(gè)星期
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();
}
//時(shí)間類 傳入
Calendar calendar = Calendar.getInstance();
//設(shè)置一周的開始為周一
calendar.setFirstDayOfWeek(Calendar.MONDAY);
//傳入需要 比對(duì)的日期
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>
預(yù)約.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:
//獲取當(dāng)前時(shí)間明郭,格式Y(jié)YYY-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;
}
//獲取是當(dāng)前星期的 日期,dayno 本周的第幾天
function getCurrentWeekDay(dayno){
var dd = new Date();
var week = dd.getDay(); //獲取時(shí)間的星期數(shù)
//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對(duì)象轉(zhuǎn)換為jquery對(duì)象
//appendDiv();//該方法的調(diào)用方在success才能保證ajax取到值之后,才循環(huán)
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>時(shí)間段</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;//標(biāo)志本次循環(huán)是否找到有相對(duì)應(yīng)的半天預(yù)約信息
if(currentOrNext==1){
day = getCurrentWeekDay(i);
}else{
day = getCurrentWeekDay(i+7);
}
//在外部循環(huán)出的日期 和丰泊,數(shù)據(jù)庫返回的預(yù)約日期 進(jìn)行匹配(上午)
$(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綁定 鼠標(biāo)移入移出事件
}
//按鈕綁定薯定,一定在ajax回調(diào)中使用,才能保證有數(shù)據(jù)
function btnbindClick(appointments){
$('.changeWeekBtn').click(function(){
if($(this).val()=='下一周'){
$('.currentWeek').css("display",'block');
$('.nextWeek').css("display",'none');
//因?yàn)橐呀?jīng)將初始化th 和上午td 下午td 分別封裝到了方法趁耗,通過最后一個(gè)參數(shù)區(qū)別本周和下一周
$('.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鼠標(biāo)移入移出事件
function tdbindHover(appointments){
$('.stateTd2').hover(function(e){
var currentApno= $(this).attr('alt')+'-'+$(this).attr('alt1');
//遍歷數(shù)據(jù)集合找到 當(dāng)前半天對(duì)應(yīng)的數(shù)據(jù)
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>';
//將內(nèi)容添加給公共的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');
});
}
});