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 Cache 造訪頁面,此方法可能無法運作。在這種情況下,我們會退而求其次,透過 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 上編輯範例