AMP

新增留言

Add comment

此時,使用者可以使用 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>

當您新增留言並點擊提交按鈕時,現在應該會看到類似以下螢幕截圖的內容