2018-10-24:Ajax完成預(yù)約效果

ajax完成預(yù)約效果

  1. 保證瀏覽器訪問action能夠得到j(luò)son數(shù)據(jù)集合(檢查瀏覽器輸出)。
  2. 先做好靜態(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)容能否正確生成表頭信息包括日期和星期幾)。
  3. 通過本周周一和周五的循環(huán)內(nèi)部和返回的數(shù)據(jù)集遍歷雙重循環(huán)歌粥,找到日期和半天匹配的信息塌忽,通過判斷生成不同的td樣式,顯示不同的界面效果(檢查本周數(shù)據(jù)是否正確生成)失驶。
  4. 將生成部分需要封裝的方法提取出來砚婆,將原來的代碼完整剪切 用function封裝,將代碼中變量不是自己聲明的就需要傳參突勇,在原位置調(diào)用方法傳參(檢查封裝后已完成功能是否受影響 如本周th装盯,td和下一周th,td逐步封裝)甲馋。
  5. 追加切換按鈕埂奈,一定要在ajax回調(diào)函數(shù)中調(diào)用方法追加。(因?yàn)閍jax 有可能先執(zhí)行但是后執(zhí)行完定躏,可能造成需要的數(shù)據(jù)集還沒有從服務(wù)器取回來)账磺,再追加封裝的click方法(檢查按鈕能不能點(diǎn)芹敌,點(diǎn)了能不能切換本周和下一周)。
  6. 通過點(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');
           });
       }
   });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市疆虚,隨后出現(xiàn)的幾起案子苛败,更是在濱河造成了極大的恐慌,老刑警劉巖径簿,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罢屈,死亡現(xiàn)場離奇詭異,居然都是意外死亡篇亭,警方通過查閱死者的電腦和手機(jī)缠捌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來译蒂,“玉大人曼月,你說我怎么就攤上這事∪嶂纾” “怎么了哑芹?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長捕透。 經(jīng)常有香客問我聪姿,道長碴萧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任末购,我火速辦了婚禮破喻,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘盟榴。我一直安慰自己曹质,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布曹货。 她就那樣靜靜地躺著咆繁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪顶籽。 梳的紋絲不亂的頭發(fā)上玩般,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音礼饱,去河邊找鬼坏为。 笑死,一個(gè)胖子當(dāng)著我的面吹牛镊绪,可吹牛的內(nèi)容都是我干的匀伏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蝴韭,長吁一口氣:“原來是場噩夢啊……” “哼够颠!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起榄鉴,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤履磨,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后庆尘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體剃诅,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年驶忌,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了矛辕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡付魔,死狀恐怖聊品,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情几苍,我是刑警寧澤杨刨,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站擦剑,受9級(jí)特大地震影響妖胀,放射性物質(zhì)發(fā)生泄漏芥颈。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧滥崩,春花似錦、人聲如沸盾计。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽署辉。三九已至,卻和暖如春岩四,著一層夾襖步出監(jiān)牢的瞬間哭尝,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國打工剖煌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留材鹦,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓耕姊,卻偏偏與公主長得像桶唐,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子茉兰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5尤泽? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 27,477評(píng)論 1 45
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,099評(píng)論 25 707
  • 今于2017年7.21號(hào)规脸,沉默中坯约,準(zhǔn)備寫一本親身經(jīng)歷的故事,同時(shí)也能幫助到每一個(gè)人
    鄒翠閱讀 168評(píng)論 0 0
  • 作者:陳宜然 我喜歡你 一對(duì)明亮的眼睛 湛藍(lán)的臉 雖然龐大 可我還是喜歡你們 如果我到了你們的王國 一定要你們 玩...
    左岸花開2020閱讀 252評(píng)論 0 0
  • 人生不怕重來网棍!這世界沒有一種成功是唾手可得的黔龟,也沒有一樣工作不辛苦,只是辛苦的方式不同滥玷。強(qiáng)者不言苦氏身,弱者才貪圖安逸...
    雪落重陽閱讀 687評(píng)論 66 42