投票
簡介
這是一個 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>
,這會在變更時提交投票。
<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 撰寫