昨天我們已經將主頁和房型介紹頁刻出來,今天就繼續製作簡易的預約列表。
我的畫面希望在昨天的房型介紹頁放入預定按鈕。小細節要注意!這個畫面都是用 axios 抓過來的,預定按鈕不能因為畫面上的其他資料還沒抓好,就先出現在網頁上:
點擊預約按鈕後,才彈出視窗讓客人能輸入資料。如果有預訂成功,要跳出"已成功預約"字樣,如果沒有預約成功,也要跳出"Oops...有東西出錯啦!"以及無法預訂的原因:

現在就讓我們開始寫吧!
今天一樣要利用六角學院的 API。開始前先釐清幾個方向:
另外我們今天也會需要設定一些 css,彈出視窗的部分則會使用到別人已寫好的程式碼,記得在 html 載入 css 檔案。
<!--這是下面自己設的css的檔名-->
<link rel="stylesheet" type="text/css" href="all.css"> 
<!--這是今天會用到的別人寫好的功能-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
為了讓大家一眼看到今天的重點,我下面已經去掉昨天打過的程式碼,只留下今天新增的部分。
<!-- 以上為<div class="roomInfo"></div>-->
<button class="book">立即預約</button>
		<!-- 下面為按完預約跳出的預約視窗-->
		<div id="preorder-form" class = "modal"> <!--彈出訂購畫面-->  
            <ul>
                <li>
                    姓名:
                    <input type="text" id="name" name="name" placeholder="請輸入姓名">
                </li>
                <li>
                    電話:
                    <input type="text" id="tel" name="tel"  placeholder="請輸入電話"> 
                </li>
                <li>
                    入住日期:
                    <input type="text" id="date" name="date"  placeholder="2020-09-27">
                </li>
                <button class = "send" onclick="sendbk()">
                    確認送出
                </button>
            </ul>   
        </div> 
<!-- 以下為<div class="amenitiesInfo row bg-light mb-5"></div>-->
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}
.modal, .book{
	display: none;
}
.send, .book{
	background-color:silver;
	color: steelblue;
}
.send:hover, .book:hover{
	background-color: steelblue;
	color: silver;
}
.modal li, .send{
	margin: 16px;
}
//原先的 axios.get 中額外加一支函式 showbtn();
axios.get(api).then((res) =>{
  roomData = res.data.room[0];
  imageCard(roomData);
  infoCard(roomData);
  amenitiesCard(roomData);
  showbtn(); //讓axios抓好東西才跑預定按鈕出來
});
//下方為預約視窗相關功能,貼在昨天的最下方即可
const modal = document.querySelector(".modal");
let orderRoomId = '';
let booking = {
  name: "",
  tel: "",
  date: []
};
const sendbk = () =>{
  booking.date = [];
  const name = document.getElementById('name');
  const tel = document.getElementById('tel');
  const date = document.getElementById('date');
  booking.name = name.value; //讓輸入的姓名成為booking這個物件的name
  booking.tel = tel.value; //同上
  booking.date.unshift(date.value); //讓輸入的日期在booking這個陣列中新增一項
  if(name.value == '' || tel.value == ''){
      alert("請輸入姓名與電話");
  }else{
      order();
      $.modal.close(); //讓彈出的視窗關掉
  }
}
const book = document.querySelector(".book");
let order = () =>{
  fetch(api,{
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization':'Bearer 放你的token'
    },
    body: JSON.stringify(booking),
    mode: 'cors',
    cache: 'no-cache'
  }).then(response=>{
    return response.json();
  }).then(json=>{
    console.log(json)
    showSuccessAlert(json)
  }).catch(err=>{
    console.log(err)
  })
}
//如果有預訂成功或失敗跳出視窗提醒使用者
const showSuccessAlert = (res)=>{
  if(res.success == true){
    alert("已成功預約");
  }else{
    alert("Oops...有東西出錯啦!"+res.message)
  }
}
function showbtn(){ //讓axios抓好東西才跑預定按鈕出來
  book.setAttribute("style","display:block"); 
}
book.addEventListener("click",function(e){ //點擊預定按鈕時彈出填資料的視窗
  $('#preorder-form').modal();
});
以上就是我們今天的教學!
JS 學徒特訓班教學影片及練習題 54 關
特別感謝: JJLee