新增留言
此時,使用者可以使用 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>
當您新增留言並按下提交按鈕時,現在應該會看到類似下列螢幕截圖的畫面