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>

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