可以在 AJAX 请求中发送标头吗?

发布于 2024-08-21 20:40:01 字数 315 浏览 2 评论 0原文

我可以通过 AJAX 请求(即页面加载后)调用服务器来设置新的 cookie 吗?

例如,当访问者点击链接时,ajax 将打开一个 php 文件,该文件设置一个新的 cookie,如下所示:

setcookie('cookiename', 'true', time()+3000, "/",'...');

但这是在 html(包含实际 标记的页面)按下之后完成的)被渲染。在ajax中设置cookie可以吗? (可能是因为加载的 php 文件与原始 html 页面是分开的)。

Can I call the server to set a new cookie with an AJAX request (that is, after the page has already loaded)?

For example, when a visitor hits a link, ajax would open a php file that sets a new cookie like this:

setcookie('cookiename', 'true', time()+3000, "/",'...');

But this is done after the html (the page containing the actual <a> tag pressed) was rendered. Is it nevertheless ok to set cookies in ajax? (maybe because the php file loaded is separate from the original html page).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月流歌 2024-08-28 20:40:01

当然,您可以让服务器的响应设置一个 cookie。请记住,cookie 是 HTTP 的东西,而不是 HTML 的东西;您的原始 HTML 文件已经在浏览器上这一事实是无关紧要的。您的 ajax 请求是对服务器的单独 HTTP 请求,该请求(希望如此!)会生成返回给浏览器的 HTTP 响应;该响应可以包含新的 Set-Cookie 标头。

我不是 PHP 人员,您需要检查用于设置 cookie 的 PHP 机制是否存在限制(我无法想象有限制)。但从根本上来说,不,这样做是没有问题的。我已经使用 JSP 和经典 ASP 完成了这项工作。

You can have the server's response set a cookie, certainly. Remember that cookies are an HTTP thing, not an HTML thing; the fact that your original HTML file is already on the browser is irrelevant. Your ajax request is a separate HTTP request to the server, which (hopefully!) generates an HTTP response back to the browser; and that response can include a new Set-Cookie header.

I'm not a PHP person, you'll need to check that there are limitations in the PHP mechanism you're using for setting the cookie (I can't imagine there are). But fundamentally, no, there's no problem doing this. I've done it with both JSPs and classic ASP.

蒲公英的约定 2024-08-28 20:40:01

我已经在我的网站上设置了 cookie 来响应 AJAX 请求,而且还没有遇到任何问题。 (虽然我没有寻找问题。)可能有些浏览器在 XmlHttpRequest 中接收 cookie 时不会设置 cookie,但到目前为止我已经看到它在 IE、Chrome 和 Firefox 中工作。

I've set cookies in the response to AJAX requests on my site and I haven't had any problems with it yet. (Although I haven't looked for problems.) It could be that some browsers don't set cookies when receiving them in an XmlHttpRequest but so far I've seen it work in IE, Chrome and Firefox.

难忘№最初的完美 2024-08-28 20:40:01

为什么不使用 javascript 来编辑 cookie?以 JSON 格式返回 cookie 的内容并使用 javascript 存储值。

Why not use javascript to edit cookies? Return the content of the cookie in JSON format and use javascript to store the values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文