2018-10-24:Ajax完成预约效果

ajax完成预约效果

  1. 保证浏览器访问action能够得到json数据集合(检查浏览器输出)。
  2. 先做好静态的表格带基本的样式,通过ajax方法,将回调函数返回的预约信息,循环变成td,组装到table中,不需要了静态的tr和td,由于涉及日期处理,需要解决如何获取当前日期,如何获取当前日期所在的周次,如何获得当前日期本周一的日期,通过将日期编号等关键信息生成到td的属性中,以便匹配(检查ajax回调函数返回的内容能否正确生成表头信息包括日期和星期几)。
  3. 通过本周周一和周五的循环内部和返回的数据集遍历双重循环,找到日期和半天匹配的信息,通过判断生成不同的td样式,显示不同的界面效果(检查本周数据是否正确生成)。
  4. 将生成部分需要封装的方法提取出来,将原来的代码完整剪切 用function封装,将代码中变量不是自己声明的就需要传参,在原位置调用方法传参(检查封装后已完成功能是否受影响 如本周th,td和下一周th,td逐步封装)。
  5. 追加切换按钮,一定要在ajax回调函数中调用方法追加。(因为ajax 有可能先执行但是后执行完,可能造成需要的数据集还没有从服务器取回来),再追加封装的click方法(检查按钮能不能点,点了能不能切换本周和下一周)。
  6. 通过点击时间和本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');
           });
       }
   });
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,088评论 1 45
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • 今于2017年7.21号,沉默中,准备写一本亲身经历的故事,同时也能帮助到每一个人
    邹翠阅读 161评论 0 0
  • 作者:陈宜然 我喜欢你 一对明亮的眼睛 湛蓝的脸 虽然庞大 可我还是喜欢你们 如果我到了你们的王国 一定要你们 玩...
    左岸花开2020阅读 231评论 0 0
  • 人生不怕重来!这世界没有一种成功是唾手可得的,也没有一样工作不辛苦,只是辛苦的方式不同。强者不言苦,弱者才贪图安逸...
    雪落重阳阅读 642评论 68 42