I create the cookie in jQuery. I can verify it in Firefox. But when I try to print the cookie or assign into another value I cant get it. I also use sessions. And I started the session in PHP. My code to print or assign the cookie value is shown below
echo $_COOKIE['a'];
for assigning the value
$b=$_COOKIE['a'];
The cookie created using jQuery is
$.cookie("a",开发者_JS百科$(this).val());
Where did I make a mistake? How can I get the cookie value?
To set the value of a cookie in PHP, use the setcookie
function:
setcookie("a", "foobar");
Doing this, however, requires that you run the code before you output to the client (and send the HTTP headers. So basically, you can't do something like this:
<div>
<p>Here's my cookie!</p>
<?php
setcookie("foo", "bar");
?>
</div>
You would need to call setcookie
before you have any of your HTML.
Also, if you set the cookie value on the client, you need to be making a request from that client to get the cookie value. If you're just running arbitrary code on the server, the client isn't sending it's cookie back up.
Lastly, the page that the server is processing and the page that the JS is on need to be in the same domain. If they're not, the browser doesn't send up the appropriate cookie.
Hope this helps!
It is possible to set the cookie in PHP entirely without jQuery at all..
..however...
It appears you are using jQuery in this way.
What may be causing a problem is a few things:
a) $(this).val()
possibly might be returning NULL.
b) You are not setting the path and expiration on the cookie. If you have subdirectories it is normally good to set a master cookie that is the root path '/'
.
To read your cookie using PHP, try this...
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
...and search the array for your "a"
cookie.
Further docs on setting and reading cookies using entirely PHP, check here.
You must call this function before any other code is echoed to the page. (before headers)
Looks fine to me. To debug the issue, try:
var_dump($_COOKIE);
and also:
List Cookies in Javascript
精彩评论