投票
简介
这是一个 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 撰写