如何设置Cookie与Ajax / jQuery?(how can set cookie with Ajax/jQuery?)

编程入门 行业动态 更新时间:2024-10-27 06:28:19
如何设置Cookie与Ajax / jQuery?(how can set cookie with Ajax/jQuery?)

我有像下面这样的ajax函数:

$.ajax({ url:"cookie.php", type: 'post', data: {'ok': val}, success:function(data) { alert(data); } });

和我的cookie.php setcookie是:

$name = "mySite"; $value = "stackoverflow.com"; setcookie($name, $value, time() + (86400 * 30), "/"); echo $name."=".$value;

与我的ajax函数mySite=stackoverflow.com显示在我的页面,但没有在浏览器中设置cookie。 为什么?

i have ajax function like below:

$.ajax({ url:"cookie.php", type: 'post', data: {'ok': val}, success:function(data) { alert(data); } });

and my cookie.php for setcookie is:

$name = "mySite"; $value = "stackoverflow.com"; setcookie($name, $value, time() + (86400 * 30), "/"); echo $name."=".$value;

with my ajax function mySite=stackoverflow.com show in my page but cookie not set in browser. why?

最满意答案

使用HTTP Set-Cookie标头Set-Cookie ,当首次加载页面时,HTTP标头会发送该标头。

该标题指示浏览器存储cookie并将其发送回服务器的未来请求中。

当您使用ajax设置Cookie时,浏览器不会重新加载当前页面,也不会发送新的标题。 相反,使用XMLHttpRequest在后台发送新请求,并且Cookie不会添加到当前页面标题中,因为新页面会重新加载并接收包含cookie的标题。

您必须重新加载页面并获取一组新的标题以查看PHP中添加的新Cookie。

还可以选择在JavaScript中设置Cookie,然后马上就可以在浏览器中看到它们。

document.cookie="mySite=stackoverflow.com; expires=Thu, 18 Dec 2015 12:00:00 UTC; path=/";

Cookies are set using the HTTP Set-Cookie header, sent in the HTTP response when a page first loads.

This header instructs the browser to store the cookie and send it back in future requests to the server.

When you set the cookie with ajax, the browser doesn't reload the current page, and no new headers are sent. Instead, a new request is sent in the background with XMLHttpRequest, and the cookies are never added to the current page headers, as that page newer reloads and receives the header containing the cookie.

You have to reload the page and get a new set of headers to see the new cookies added in PHP.

There's also the option of setting the cookies in javascript, then they would be visible in the browser right away.

document.cookie="mySite=stackoverflow.com; expires=Thu, 18 Dec 2015 12:00:00 UTC; path=/";

更多推荐

本文发布于:2023-07-26 18:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何设置   Cookie   Ajax   cookie   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!