仅在查看特定页面时存在的 cookie?
标题说明了一切。我想使用 cookie 将一些特定于他正在查看的当前页面的元数据发送到客户端。我不想将其放在 HTML 中,主要是因为只有在生成所有 HTML 并且结束 标记就位后才计算元数据。
以前,我只是将其粘贴在最终 之后的隐藏
中,浏览器似乎可以很好地渲染它,但我想在使用符合标准的 HTML 时执行相同的操作。虽然我希望每当客户端对服务器进行 ajax 调用时都会发回 cookie,但我希望它在离开页面后立即失效。
The title ways it all. I want to use a cookie to send some metadata over to the client that is specific to the current page he is viewing. I'd rather not put it in the HTML, mainly because the metadata is only calculated after all the HTML is already generated and the closing </html>
tag is in place.
Previously I was simply sticking it in a hidden <input/>
after the final </html>
, and browsers seem to render it fine, but I want to do the same thing while having standards compliant HTML. Although I want the cookie to be sent back whenever the client makes an ajax call to the server, I want it to invalidate immediately upon leaving the page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果页面位于唯一路径中(或者可以这样进行 URL 重写),则只需将 cookie 的
path
属性设置为页面的完整路径即可。仅当页面 URL 被 cookie 的path
覆盖时,浏览器才会发回 cookie。或者,根据具体的功能需求,您也可以考虑使用 HTML5 数据属性 。
If the page is in an unique path (or can be URL-rewritten as such), then just set the cookie's
path
attribute to the page's full path. The browser will send the cookie only back whenever the page URL is covered by the cookie'spath
.Alternatively, depending on the concrete functional requirement, you could also consider using the HTML5 data attributes.