添加评论
此时,用户可以使用 amp-form
库添加评论。 请注意,表单的存在是有条件的,这取决于 amp-access
组件的状态
<form amp-access="loggedIn" amp-access-hide method="post" action-xhr="<%host%>/samples_templates/comment_section/submit-comment-xhr" target="_top">
我们指定了一个 POST 方法和一个 XHR 操作,因为在 AMP 中 POST 方法不允许使用非 XHR 操作。 因为这是一个演示,我们不持久化评论,所以一次只能添加一条评论; 每当添加评论时,AMPByExample 服务器都会回复一个 JSON 响应,其中包含输入的文本以及一些其他信息,例如时间戳、头像和用户的名称。
这是一个 JSON 响应示例
{"Datetime":"09:34:21", "User":"Charlie", "Text":"Hello!", "UserImg":"/img/ic_account_box_black_48dp_1x.png"}
表单组件将使用 amp-mustache
模板简单地在页面内显示这些值
<div submit-success> <template type="amp-mustache"> <div class="comment-user"> <amp-img width="44" class="user-avatar" height="44" alt="user" src=""></amp-img> <div class="card comment"> <p><span class="user">{{User}}</span><span class="date">{{Datetime}}</span></p> <p>{{Text}}</p> </div> </div> </template> </div>
在此示例中,我们仅检查评论的值是否为空; 如果值为空,我们将返回一个错误,该错误将导致执行以下代码
<div submit-error> <template type="amp-mustache"> Error! Looks like something went wrong with your comment, please try to submit it again. </template> </div>
作为额外的一点,我们添加了 required
属性,以强制在提交评论之前必须填写评论文本
<input type="text" class="data-input" name="text" placeholder="Your comment..." required>
当你添加评论并单击提交按钮时,你应该看到类似于以下屏幕截图的内容