投票
简介
这是一个 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.org.cn/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 编写