AMP
  • 網站

投票

簡介

這是 AMP 投票範本。選取其中一個答案後,您會看到所選答案的百分比。

設定

匯入其他 AMP 元件。此範例使用 amp-form 接受投票回覆。

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

此範例使用 Mustache 範本來格式化投票結果

<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>

投票

我們使用 amp-form 實作投票功能。為了避免同一位使用者重複投票,我們需要識別哪些使用者已投票。我們使用名為 POLL_USER_ID 的 Cookie 來識別使用者。考量到 Safari 的預設行為是封鎖來自先前未曾造訪網站的第三方 Cookie,如果透過 AMP 快取造訪網頁,此方法可能無法運作。在這種情況下,我們會改為透過 CLIENT_ID 檢查重複的項目。

CLIENT_ID 是使用者在存取特定來源 (例如原始網頁或快取版本) 時的專屬識別碼。這表示同一位使用者在存取不同來源時,會產生兩個不同的值。這就是我們使用自訂 Cookie 來追蹤跨來源存取投票網頁的原因。

深入瞭解變數替換。目前表單回覆不支援 HTML 表格,因此我們會使用 CSS 來配置結果資料。

深入瞭解變數替換

為了在使用者選擇選項後立即提交表單,我們會新增一個

on 屬性到每個 <input>,這會在變更時提交投票。

您最喜歡的不会飛的鳥類是什麼?

選擇您最喜歡的不会飛的鳥類,您將發現其他使用者選擇了什麼。如果您已投票,您的答案將被覆寫。

錯誤!您的投票似乎發生錯誤,請再次嘗試提交。{{error}}
<form id="sample-poll" method="post" action-xhr="https://amp.dev.org.tw/documentation/examples/interactivity-dynamic-content/poll/submit-poll" target="_blank">
      <input name="clientId" type="hidden" value="CLIENT_ID(POLL_USER_ID)" data-amp-replace="CLIENT_ID">
      <h3>What is your favorite flightless bird?</h3>
      <p>Choose your favourite flightless bird and you will discover what other users have chosen.
      If you have already voted, your answer will be overwritten.</p>
      <label>Penguins <input type="radio" value="0" name="answer" on="change:sample-poll.submit"></label>
      <label>Ostriches <input type="radio" value="1" name="answer" on="change:sample-poll.submit"></label>
      <label>Kiwis <input type="radio" value="2" name="answer" on="change:sample-poll.submit"></label>
      <label>Wekas <input type="radio" value="3" name="answer" on="change:sample-poll.submit"></label>
      <div submit-success>
        <script type="text/plain" template="amp-mustache">
          <p>{{Message}}</p>
          <p>Here are the results:</p>
          <table>
            {{#PollEntryResults}}
            <tr>
              <td>
                {{Answer}}
              </td>
              <td>
                {{Percentage.length}}%
              </td>
              <td>
                {{Votes}}
              </td>
              <td>
                {{#Percentage}}<span class="one-pc-fixed"></span>{{/Percentage}}
              </td>
            </tr>
            {{/PollEntryResults}}
          </table>
        </script>
      </div>
      <div submit-error>
        Error! Looks like something went wrong with your vote, please try to submit it again. {{error}}
      </div>
</form>
需要進一步說明嗎?

如果此頁面的說明未能涵蓋您的所有問題,請隨時與其他 AMP 使用者交流,討論您的確切使用案例。

前往 Stack Overflow
未說明的特色功能?

AMP 專案非常鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎您針對您特別感興趣的問題做出一次性貢獻。

在 GitHub 上編輯範例