投票
简介
这是 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