admin管理员组

文章数量:1296915

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";
setcookie($name, $value, time() + (86400 * 30), "/");
echo $name."=".$value;

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

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.";
setcookie($name, $value, time() + (86400 * 30), "/");
echo $name."=".$value;

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

Share Improve this question asked Apr 2, 2015 at 16:09 kellykelly 673 silver badges8 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

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.; expires=Thu, 18 Dec 2015 12:00:00 UTC; path=/";

本文标签: javascripthow can set cookie with AjaxjQueryStack Overflow