2018-10-24:Ajax完成預約效果

weixin_33749242發表於2018-10-25

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');
           });
       }
   });

相關文章