投票
簡介
這是一個 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>`,這將在變更時提交投票。
<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 上編輯範例-
作者: @aghassemi