新增留言
此時,使用者可以使用 amp-form
函式庫新增留言。請注意表單的存在是有條件的,取決於 amp-access
元件的狀態
<form amp-access="loggedIn" amp-access-hide method="post" action-xhr="<%host%>/samples_templates/comment_section/submit-comment-xhr" target="_top">
我們指定了 POST 方法和 XHR 動作,因為在 AMP 中不允許 POST 方法使用非 XHR 動作。由於這是一個示範,我們不會持久儲存留言,因此一次只能新增一個留言;每當新增留言時,AMPByExample 伺服器都會回覆一個 JSON 回應,其中包含輸入的文字以及一些額外資訊,例如時間戳記、頭像和使用者名稱。
以下是 JSON 回應的範例
{"Datetime":"09:34:21", "User":"Charlie", "Text":"Hello!", "UserImg":"/img/ic_account_box_black_48dp_1x.png"}
表單元件將僅使用 amp-mustache
範本在頁面中顯示這些值
<div submit-success> <template type="amp-mustache"> <div class="comment-user"> <amp-img width="44" class="user-avatar" height="44" alt="user" src=""></amp-img> <div class="card comment"> <p><span class="user">{{User}}</span><span class="date">{{Datetime}}</span></p> <p>{{Text}}</p> </div> </div> </template> </div>
在本範例中,我們僅檢查留言的值是否為空;如果值為空,我們將傳回一個錯誤,導致以下程式碼執行
<div submit-error> <template type="amp-mustache"> Error! Looks like something went wrong with your comment, please try to submit it again. </template> </div>
為了更完善,我們新增了 required
屬性,以強制要求在提交留言之前必須填寫留言文字
<input type="text" class="data-input" name="text" placeholder="Your comment..." required>
當您新增留言並點擊提交按鈕時,您現在應該會看到類似以下螢幕截圖的內容